If CSS3 is an option (or you have a fallback) you can use transform:
.center {
right: 50%;
bottom: 50%;
transform: translate(50%,50%);
position: absolute;
}
Unlike the first approach above, you don't want to use left:50% with the negative translation because there's an overflow bug in IE9+. Utilize a positive right value and you won't see horizontal scrollbars.
Use ifelse
:
frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
data twohouses
1 0 1
2 1 1
3 2 2
4 3 2
5 4 2
...
16 0 1
17 2 2
18 1 1
19 2 2
20 0 1
21 4 2
The difference between if
and ifelse
:
if
is a control flow statement, taking a single logical value as an argumentifelse
is a vectorised function, taking vectors as all its arguments.The help page for if
, accessible via ?"if"
will also point you to ?ifelse
1) git branch --set-upstream-to=origin/<master_branch>
feature/<your_current_branch>
2) git pull
I would use jQuery to get the results that you're looking for. You wouldn't need to use an anchor tag at that point but if you did it would look like:
<a href="page" style="text-decoration:none;display:block;">
<span onclick="hide()">Hide me</span>
</a>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.2.min.js' /
<script type='text/javascript'>
$(document).ready(function(){
$('span').click(function(){
$(this).hide();
}
}
(Note: An official API was added in API 14: See this answer https://stackoverflow.com/a/29786451/119733)
DO NOT USE PREVIOUS (waqas716) answer.
You will have memory leak problem, because of the static reference to the activity. For more detail see the following link http://android-developers.blogspot.fr/2009/01/avoiding-memory-leaks.html
To avoid this, you should manage activities references. Add the name of the application in the manifest file:
<application
android:name=".MyApp"
....
</application>
Your application class :
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private Activity mCurrentActivity = null;
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
Create a new Activity :
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (this.equals(currActivity))
mMyApp.setCurrentActivity(null);
}
}
So, now instead of extending Activity class for your activities, just extend MyBaseActivity. Now, you can get your current activity from application or Activity context like that :
Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity();
1.
long date = curDateFld.getDate();
//convert long to string
String str = String.valueOf(date);
//convert string to long
date = Long.valueOf(str);
2.
//convert long to string just concat long with empty string
String str = ""+date;
//convert string to long
date = Long.valueOf(str);
Open app page on Google Play:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + context.getPackageName()));
startActivity(intent);
You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>
.
Also make sure you change your id
#rotate
to a class since you have multiple.
$(document).ready(function() {_x000D_
$('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
border-collapse: collapse;_x000D_
border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
/* FF3.5+ */_x000D_
-moz-transform: rotate(-90.0deg);_x000D_
/* Opera 10.5 */_x000D_
-o-transform: rotate(-90.0deg);_x000D_
/* Saf3.1+, Chrome */_x000D_
-webkit-transform: rotate(-90.0deg);_x000D_
/* IE6,IE7 */_x000D_
filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
/* IE8 */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
/* Standard */_x000D_
transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>10kg</div>_x000D_
</td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>20kg</div>_x000D_
</td>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>30kg</div>_x000D_
</td>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
JavaScript
The equivalent to the above in pure JavaScript is as follows:
window.addEventListener('load', function () {
var rotates = document.getElementsByClassName('rotate');
for (var i = 0; i < rotates.length; i++) {
rotates[i].style.height = rotates[i].offsetWidth + 'px';
}
});
Try using a div tag and block for span!
<div>
<span style="padding-right:3px; padding-top: 3px; display:block;">
<img class="manImg" src="images/ico_mandatory.gif"></img>
</span>
</div>
This is a bit nasty, but:
from datetime import datetime, timedelta
now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()
I think I have the solution to your question, assuming you can use flexbox in your project. What you want to do is make #one
a flexbox using display: flex
and use flex-direction: column
to make it a column alignment.
html,_x000D_
body {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.border {_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.margin {_x000D_
margin: 5px;_x000D_
}_x000D_
_x000D_
#one {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
#two {_x000D_
height: 50px;_x000D_
}_x000D_
_x000D_
#three {_x000D_
width: 100px;_x000D_
height: 100%;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="one" class="border">_x000D_
<div id="two" class="border margin"></div>_x000D_
<div id="three" class="border margin"></div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
For Python3.x and starting Pillow==6.0.0
, Image
objects now provide a getexif()
method that returns a <class 'PIL.Image.Exif'>
instance or None
if the image has no EXIF data.
From Pillow 6.0.0 release notes:
getexif()
has been added, which returns anExif
instance. Values can be retrieved and set like a dictionary. When saving JPEG, PNG or WEBP, the instance can be passed as anexif
argument to include any changes in the output image.
As stated, you can iterate over the key-value pairs of the Exif
instance like a regular dictionary. The keys are 16-bit integers that can be mapped to their string names using the ExifTags.TAGS
module.
from PIL import Image, ExifTags
img = Image.open("sample.jpg")
img_exif = img.getexif()
print(type(img_exif))
# <class 'PIL.Image.Exif'>
if img_exif is None:
print('Sorry, image has no exif data.')
else:
for key, val in img_exif.items():
if key in ExifTags.TAGS:
print(f'{ExifTags.TAGS[key]}:{val}')
# ExifVersion:b'0230'
# ...
# FocalLength:(2300, 100)
# ColorSpace:1
# ...
# Model:'X-T2'
# Make:'FUJIFILM'
# LensSpecification:(18.0, 55.0, 2.8, 4.0)
# ...
# DateTime:'2019:12:01 21:30:07'
# ...
Tested with Python 3.8.8 and Pillow==8.1.0
.
If you want an example of a world generator simulation plates tectonics, erosion, rain-shadow, etc. take a look at: https://github.com/ftomassetti/lands
On top of that there is also a civilizations evolution simulator:
https://github.com/ftomassetti/civs
A blog full on interesting resource is:
dungeonleague.com/
It is abandoned now but you should read all its posts
The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.
If you're on C# 7, you should consider using value tuples as your composite key. Value tuples typically offer better performance than the traditional reference tuples (Tuple<T1, …>
) since value tuples are value types (structs), not reference types, so they avoid the memory allocation and garbage collection costs. Also, they offer conciser and more intuitive syntax, allowing for their fields to be named if you so wish. They also implement the IEquatable<T>
interface needed for the dictionary.
var dict = new Dictionary<(int PersonId, int LocationId, int SubjectId), string>();
dict.Add((3, 6, 9), "ABC");
dict.Add((PersonId: 4, LocationId: 9, SubjectId: 10), "XYZ");
var personIds = dict.Keys.Select(k => k.PersonId).Distinct().ToList();
Based in @Daniel answer I did:
for remote in \`git branch | grep -v master\`
do
git push -u origin $remote
done
I had this issue recently,
Problem statement: Mine was a windows service that I run locally by attaching VS debugger. When I stop debugging and try to restart/stop the service (under services.msc) I used to get the mentioned error.
Solution:
On doing the above the service is stopped.
I have managed to modify some of @alpiii's code and discovered that List comprehension is a little faster than for loop. It might be caused by int()
, it is not fair between list comprehension and for loop.
from functools import reduce
import datetime
def time_it(func, numbers, *args):
start_t = datetime.datetime.now()
for i in range(numbers):
func(args[0])
print (datetime.datetime.now()-start_t)
def square_sum1(numbers):
return reduce(lambda sum, next: sum+next*next, numbers, 0)
def square_sum2(numbers):
a = []
for i in numbers:
a.append(i*2)
a = sum(a)
return a
def square_sum3(numbers):
sqrt = lambda x: x*x
return sum(map(sqrt, numbers))
def square_sum4(numbers):
return(sum([i*i for i in numbers]))
time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
0:00:00.101122 #Reduce
0:00:00.089216 #For loop
0:00:00.101532 #Map
0:00:00.068916 #List comprehension
If compileOptions doesn't work, try this
Disable 'Instant Run'.
Android Studio -> File -> Settings -> Build, Execution, Deployment -> Instant Run -> Disable checkbox
This is all you need.
rsync -e ssh file host:/directory/.
If the problem is not solved by above answer, check whether the Windows SDK version is 10.0.15063.0.
Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0
After this rebuild the solution.
My understanding is that the SQL standard calls for case-insensitivity. I don't believe any databases follow the standard completely, though.
MySQL has a configuration setting as part of its "strict mode" (a grab bag of several settings that make MySQL more standards-compliant) for case sensitive or insensitive table names. Regardless of this setting, column names are still case-insensitive, although I think it affects how the column-names are displayed. I believe this setting is instance-wide, across all databases within the RDBMS instance, although I'm researching today to confirm this (and hoping the answer is no).
I like how Oracle handles this far better. In straight SQL, identifiers like table and column names are case insensitive. However, if for some reason you really desire to get explicit casing, you can enclose the identifier in double-quotes (which are quite different in Oracle SQL from the single-quotes used to enclose string data). So:
SELECT fieldName
FROM tableName;
will query fieldname from tablename, but
SELECT "fieldName"
FROM "tableName";
will query fieldName from tableName.
I'm pretty sure you could even use this mechanism to insert spaces or other non-standard characters into an identifier.
In this situation if for some reason you found explicitly-cased table and column names desirable it was available to you, but it was still something I would highly caution against.
My convention when I used Oracle on a daily basis was that in code I would put all Oracle SQL keywords in uppercase and all identifiers in lowercase. In documentation I would put all table and column names in uppercase. It was very convenient and readable to be able to do this (although sometimes a pain to type so many capitals in code -- I'm sure I could've found an editor feature to help, here).
In my opinion MySQL is particularly bad for differing about this on different platforms. We need to be able to dump databases on Windows and load them into UNIX, and doing so is a disaster if the installer on Windows forgot to put the RDBMS into case-sensitive mode. (To be fair, part of the reason this is a disaster is our coders made the bad decision, long ago, to rely on the case-sensitivity of MySQL on UNIX.) The people who wrote the Windows MySQL installer made it really convenient and Windows-like, and it was great to move toward giving people a checkbox to say "Would you like to turn on strict mode and make MySQL more standards-compliant?" But it is very convenient for MySQL to differ so signficantly from the standard, and then make matters worse by turning around and differing from its own de facto standard on different platforms. I'm sure that on differing Linux distributions this may be further compounded, as packagers for different distros probably have at times incorporated their own preferred MySQL configuration settings.
Here's another SO question that gets into discussing if case-sensitivity is desirable in an RDBMS.
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
http://en.cppreference.com/w/cpp/memory/weak_ptr std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.
std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership. If the original std::shared_ptr is destroyed at this time, the object's lifetime is extended until the temporary std::shared_ptr is destroyed as well.
In addition, std::weak_ptr is used to break circular references of std::shared_ptr.
Berkelium is a C++ tool for making chrome embeddable.
AwesomiumDotNet is a wrapper around both Berkelium and Awesomium
BTW, the link here to Awesomium appears to be more current.
127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.
-Xmn : the size of the heap for the young generation Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor" .
Good size is 33%
Here is an illustration of your first import cycle problem.
project/controllers/account
^ \
/ \
/ \
/ \/
project/components/mux <--- project/controllers/base
As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux
imports project/controllers/account
. Since Go does not support circular dependencies you get the import cycle not allowed
error during compile time.
I have some code in my game that displays live score. It is in a function for quick access.
def texts(score):
font=pygame.font.Font(None,30)
scoretext=font.render("Score:"+str(score), 1,(255,255,255))
screen.blit(scoretext, (500, 457))
and I call it using this in my while loop:
texts(score)
C++ places the default parameter logic in the calling side, this means that if the default value expression cannot be computed from the calling place, then the default value cannot be used.
Other compilation units normally just include the declaration so default value expressions placed in the definition can be used only in the defining compilation unit itself (and after the definition, i.e. after the compiler sees the default value expressions).
The most useful place is in the declaration (.h) so that all users will see it.
Some people like to add the default value expressions in the implementation too (as a comment):
void foo(int x = 42,
int y = 21);
void foo(int x /* = 42 */,
int y /* = 21 */)
{
...
}
However, this means duplication and will add the possibility of having the comment out of sync with the code (what's worse than uncommented code? code with misleading comments!).
Simply
pip show numpy
and for pip3
pip3 show numpy
Works on both windows and linux. Should work on mac too if you are using pip.
I found that "@RequestMapping produces=" and other configuration changes didn't help me. By the time you do resp.getWriter(), it is also too late to set the encoding on the writer.
Adding a header to the HttpServletResponse works.
@RequestMapping(value="/test", method=RequestMethod.POST)
public void test(HttpServletResponse resp) {
try {
resp.addHeader("content-type", "application/json; charset=utf-8");
PrintWriter w = resp.getWriter();
w.write("{\"name\" : \"µr µicron\"}");
w.flush();
w.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Assuming
source data range is A1:B100.
query cell is D1 (here you will input Police or Fire).
result cell is E1
Formula in E1 = VLOOKUP(D1, A1:B100, 2, FALSE)
It's not in standard C, so the behavior is undefined.
Some implementation uses it to clear stdin
buffer.
From C11 7.21.5.2 The fflush function, fflush
works only with output/update stream, not input stream.
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
It is possible to use your usual System.Configuration
even in .NET Core 2.0 on Linux. Try this test example:
MyLib.dll
)System.Configuration.ConfigurationManager
v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library
v2.0.0 (I hope that changes)ConfigurationSection
or ConfigurationElement
go into MyLib.dll
. For example MyClass.cs
derives from ConfigurationSection
and MyAccount.cs
derives from ConfigurationElement
. Implementation details are out of scope here but Google is your friend.MyApp.dll
). .NET Core apps end with .dll
rather than .exe
in Framework.app.config
in MyApp
with your custom configuration sections. This should obviously match your class designs in #3 above. For example:<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
</configSections>
<myCustomConfig>
<myAccount id="007" />
</myCustomConfig>
</configuration>
That's it - you'll find that the app.config is parsed properly within MyApp
and your existing code within MyLib
works just fine. Don't forget to run dotnet restore
if you switch platforms from Windows (dev) to Linux (test).
Additional workaround for test projects
If you're finding that your App.config
is not working in your test projects, you might need this snippet in your test project's .csproj
(e.g. just before the ending </Project>
). It basically copies App.config
into your output folder as testhost.dll.config
so dotnet test
picks it up.
<!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
</Target>
<!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
First, close all instances of Google Chrome. There should be no instances of chrome.exe
running in the Windows Task Manager. Then
%LOCALAPPDATA%\Google\Chrome\User Data\Default\
..txt
). This will serve as a backup, should something go wrong.window_placement
. Under window_placement
you will see things like "bottom", "left", "right", etc. with numbers after them.You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.
Give this a try:
$(document).ready(function(){
$("#topbar-show").toggle(function(){
$(this).animate({height:40},200);
},function(){
$(this).animate({height:10},200);
});
});
Escaping parameters like that is usually source of frustration and feels a lot like a time wasted. I see you're on v2 so I would suggest using a technique that Joel "Jaykul" Bennet blogged about a while ago.
Long story short: you just wrap your string with @' ... '@ :
Start-Process \\server\toto.exe @'
-batch=B -param="sort1;parmtxt='Security ID=1234'"
'@
(Mind that I assumed which quotes are needed, and which things you were attempting to escape.) If you want to work with the output, you may want to add the -NoNewWindow
switch.
BTW: this was so important issue that since v3 you can use --%
to stop the PowerShell parser from doing anything with your parameters:
\\server\toto.exe --% -batch=b -param="sort1;paramtxt='Security ID=1234'"
... should work fine there (with the same assumption).
The more general answer is
UPDATE mysql.user SET host = {newhost} WHERE user = {youruser}
The usual trick is to make the image itself part of a link instead of a button. Then, you bind the "click" event with a custom handler.
Frameworks like Jquery-UI or Bootstrap does this out of the box. Using one of them may ease a lot the whole application conception by the way.
How to easily throttle to a specific FPS:
// timestamps are ms passed since document creation.
// lastTimestamp can be initialized to 0, if main loop is executed immediately
var lastTimestamp = 0,
maxFPS = 30,
timestep = 1000 / maxFPS; // ms for each frame
function main(timestamp) {
window.requestAnimationFrame(main);
// skip if timestep ms hasn't passed since last frame
if (timestamp - lastTimestamp < timestep) return;
lastTimestamp = timestamp;
// draw frame here
}
window.requestAnimationFrame(main);
Source: A Detailed Explanation of JavaScript Game Loops and Timing by Isaac Sukin
I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:
class Zoo<T extends Animal> {
constructor(public readonly AnimalClass: new () => T) {
}
}
This way variables penguin
and lion
infer concrete type Penguin
or Lion
even in the TypeScript intellisense.
const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.
const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
First Div
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
Second Div
</div>
</div>
This does the trick.
ExcelDiff exports a HTML report in a Divided (Side-by-side) or Merged (Overlay) view highlighting the differences as well as the row and column.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.setAttribute("style","color:red;font-size:23px");
btn.appendChild(t);
document.body.appendChild(btn);
btn.setAttribute("onclick", alert("clicked"));
}
</script>
</body>
</html>
You can find more about it in the bundler website (emphasis added below for your convenience):
After developing your application for a while, check in the application together with the Gemfile and Gemfile.lock snapshot. Now, your repository has a record of the exact versions of all of the gems that you used the last time you know for sure that the application worked...
This is important: the Gemfile.lock makes your application a single package of both your own code and the third-party code it ran the last time you know for sure that everything worked. Specifying exact versions of the third-party code you depend on in your Gemfile would not provide the same guarantee, because gems usually declare a range of versions for their dependencies.
The black div
will display the full 500px unless overflow:hidden
is set on the 100px li
I had to add a .toString
to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm
.
function foo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('spreadsheet-name');
var r = s.getRange('A:A');
var v = r.getValues();
var searchTerm = 'needle';
for(var i=v.length-1;i>=0;i--) {
if(v[0,i].toString().indexOf(searchTerm) > -1) {
// do something
}
}
};
Please for the love of the internet use string concatenation and opt not to use ES6 solutions for this. ES6 is NOT supported all across the board, much like CSS3 and certain browsers being slow to adapt to the CSS3 movement. Use plain ol' JavaScript, your end users will thank you.
Example:
var str = "This world is neither flat nor round. "+
"Once was lost will be found";
MySql does not have FULL-OUTER-JOIN syntax. You have to emulate by doing both LEFT JOIN and RIGHT JOIN as follows-
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
But MySql also does not have a RIGHT JOIN syntax. According to MySql's outer join simplification, the right join is converted to the equivalent left join by switching the t1 and t2 in the FROM
and ON
clause in the query. Thus, the MySql Query Optimizer translates the original query into the following -
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t2
LEFT JOIN t1 ON t2.id = t1.id
Now, there is no harm in writing the original query as is, but say if you have predicates like the WHERE clause, which is a before-join predicate or an AND predicate on the ON
clause, which is a during-join predicate, then you might want to take a look at the devil; which is in details.
MySql query optimizer routinely checks the predicates if they are null-rejected. Now, if you have done the RIGHT JOIN, but with WHERE predicate on the column from t1, then you might be at a risk of running into a null-rejected scenario.
For example, THe following query -
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
WHERE t1.col1 = 'someValue'
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
WHERE t1.col1 = 'someValue'
gets translated to the following by the Query Optimizer-
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
WHERE t1.col1 = 'someValue'
UNION
SELECT * FROM t2
LEFT JOIN t1 ON t2.id = t1.id
WHERE t1.col1 = 'someValue'
So the order of tables has changed, but the predicate is still applied to t1, but t1 is now in the 'ON' clause. If t1.col1 is defined as NOT NULL
column, then this query will be null-rejected.
Any outer-join (left, right, full) that is null-rejected is converted to an inner-join by MySql.
Thus the results you might be expecting might be completely different from what the MySql is returning. You might think its a bug with MySql's RIGHT JOIN, but thats not right. Its just how the MySql query-optimizer works. So the developer-in-charge has to pay attention to these nuances when he is constructing the query.
It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.
In Web API, it's very simple to remember how parameter binding is happening.
POST
simple types, Web API tries to bind it from the URL if you POST
complex type, Web API tries to bind it from the body of
the request (this uses a media-type
formatter).
If you want to bind a complex type from the URL, you'll use [FromUri]
in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.
public IHttpActionResult Put([FromUri] ViewModel data) { ... }
If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.
public IHttpActionResult Put([FromBody] string name) { ... }
as a side note, say you are making a PUT
request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data
parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.
var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});
and your web api action will look something like below.
public IHttpActionResult Put([FromBody] string name){ ... }
This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Since you are selecting multiple tables, The table to delete from is no longer unambiguous. You need to select:
DELETE posts FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
In this case, table_name1
and table_name2
are the same table, so this will work:
DELETE projects FROM posts INNER JOIN [...]
You can even delete from both tables if you wanted to:
DELETE posts, projects FROM posts INNER JOIN [...]
Note that order by
and limit
don't work for multi-table deletes.
Also be aware that if you declare an alias for a table, you must use the alias when referring to the table:
DELETE p FROM posts as p INNER JOIN [...]
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
if you have a parameter $string
and want to replace it's apace to underscore(_).
$string = "Hello All.";
$newString = str_replace(' ', '_', $string);
output will be Hello_All.
Try this:
function reload(){_x000D_
var container = document.getElementById("yourDiv");_x000D_
var content = container.innerHTML;_x000D_
container.innerHTML= content; _x000D_
_x000D_
//this line is to watch the result in console , you can remove it later _x000D_
console.log("Refreshed"); _x000D_
}
_x000D_
<a href="javascript: reload()">Click to Reload</a>_x000D_
<div id="yourDiv">The content that you want to refresh/reload</div>
_x000D_
Hope it works. Let me know
This worked for me
if (assoc_pagine[var] != undefined) {
instead this
if (assoc_pagine[var] != "undefined") {
You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).
These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:
class Book {
private String title; // not nullable
private String isbn; // nullable
// Here we provide a default value, but we could also skip the
// parameterless constructor entirely, to force users of the class to
// provide a title
public Book()
{
this("Untitled");
}
public Book(String title) throws IllegalArgumentException
{
if (title == null)
throw new IllegalArgumentException("Book title can't be null");
this.title = title;
// leave isbn without value
}
// Constructor with title and isbn
}
However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question.
Hardiff.com is pretty useful tool. It allows you to compare one or more .har
files.
You can try this VBA program
Option Explicit
Sub CopyWorksheetsFomTemplate()
Dim NewName As String
Dim nm As Name
Dim ws As Worksheet
If MsgBox("Copy specific sheets to a new workbook" & vbCr & _
"New sheets will be pasted as values, named ranges removed" _
, vbYesNo, "NewCopy") = vbNo Then Exit Sub
With Application
.ScreenUpdating = False
' Copy specific sheets
' *SET THE SHEET NAMES TO COPY BELOW*
' Array("Sheet Name", "Another sheet name", "And Another"))
' Sheet names go inside quotes, seperated by commas
On Error GoTo ErrCatcher
Sheets(Array("Sheet1", "Sheet2")).Copy
On Error GoTo 0
' Paste sheets as values
' Remove External Links, Hperlinks and hard-code formulas
' Make sure A1 is selected on all sheets
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.Copy
ws.[A1].PasteSpecial Paste:=xlValues
ws.Cells.Hyperlinks.Delete
Application.CutCopyMode = False
Cells(1, 1).Select
ws.Activate
Next ws
Cells(1, 1).Select
' Remove named ranges
For Each nm In ActiveWorkbook.Names
nm.Delete
Next nm
' Input box to name new file
NewName = InputBox("Please Specify the name of your new workbook", "New Copy")
' Save it with the NewName and in the same directory as original
ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & NewName & ".xls"
ActiveWorkbook.Close SaveChanges:=False
.ScreenUpdating = True
End With
Exit Sub
ErrCatcher:
MsgBox "Specified sheets do not exist within this workbook"
End Sub
$colsRequired = ["apple", "orange", "banana", "grapes"];
$data = ["apple"=>"some text", "orange"=>"some text"];
$presentInBoth = array_intersect($colsRequired,array_keys($data));
if( count($presentInBoth) != count($colsRequired))
echo "Missing keys :" . join(",",array_diff($colsRequired,$presentInBoth));
else
echo "All Required cols are present";
Use sqlcmd instead of osql if it's a 2005 database
I was having this problem when I started using select2 with XCrud. I solved it by disabling XCrud from loading JQuery, it was it a second time, and loading it below the body tag. So make sure JQuery isn't getting loaded twice on your page.
Another option is to run ng serve
command with the --port
option e.g
ng serve --port 5050
(i.e for port 5050)
Alternatively, the command: ng serve --port 0
, will auto assign an available port for use.
I tried above and nothing worked for me. Following code is from socket.io documentation and it worked.
io.origins((origin, callback) => {
if (origin !== 'https://foo.example.com') {
return callback('origin not allowed', false);
}
callback(null, true);
});
Both if (one.length() > 0) {}
and if (!"".equals(one)) {}
will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo
text field.
If there's any chance you can use the Expression Language to handle the parameter, you could
access it with empty param.foo
in an expression.
<c:if test='${not empty param.foo}'>
This page code gets rendered.
</c:if>
It's possible to get this done using seaborn.lineplot()
but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:
# imports
import seaborn as sns
import numpy as np
import pandas as pd
# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])
# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)
# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>
And we get the following plot:
sed
If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed
command once the (X)HTML has been created from Markdown:
sed -i 's|href="http|target="_blank" href="http|g' index.html
This can be further automated in a single workflow when a Makefile
with build instructions is employed.
PS: This answer was written at a time when extension link_attributes
was not yet available in Pandoc.
you can set your logging configuration file through command line:
$ java -Djava.util.logging.config.file=/path/to/app.properties MainClass
this way seems cleaner and easier to maintain.
#container-of-boxes {
display: table;
width: 1158px;
}
#box-1 {
width: 578px;
}
#box-2 {
width: 386px;
}
#box-3 {
width: 194px;
}
#box-1, #box-2, #box-3 {
min-height: 210px;
padding-bottom: 20px;
display: table-cell;
height: auto;
overflow: hidden;
}
If you are using Eclipse,
They should all be in there. Right click and "checkout."
I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(
//open upload window upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);
You could try a for loop
for func,args,kwargs in zip([a,b,c,d],
[args_a,args_b,args_c,args_d],
[kw_a,kw_b,kw_c,kw_d]):
try:
func(*args, **kwargs)
break
except:
pass
This way you can loop as many functions as you want without making the code look ugly
From stack trace:
HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.
The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.
Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.
otherwise, your maximum connections 'at a time' requirement is higher than 20 !
You could use a pseudo element for this, and have your image on a hover:
.image {_x000D_
position: relative;_x000D_
height: 300px;_x000D_
width: 300px;_x000D_
background: url(http://lorempixel.com/300/300);_x000D_
}_x000D_
.image:before {_x000D_
content: "";_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
transition: all 0.8s;_x000D_
opacity: 0;_x000D_
background: url(http://lorempixel.com/300/200);_x000D_
background-size: 100% 100%;_x000D_
}_x000D_
.image:hover:before {_x000D_
opacity: 0.8;_x000D_
}
_x000D_
<div class="image"></div>
_x000D_
? TWO Simple Solutions:
To install the latest version of node and reinstall the old version packages just run the following command.
nvm install node --reinstall-packages-from=node
To install the latest lts
(long term support) version of node and reinstall the old version packages just run the following command.
nvm install --lts /* --reinstall-packages-from=node
Here's a GIF to support this answer.
Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:
private DataTable LoadExcelData(string fileName)
{
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);
myCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
return dt;
}
You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.
You can do kubectl get replicasets
check for old deployment based on age or time
Delete old deployment based on time if you want to delete same current running pod of application
kubectl delete replicasets <Name of replicaset>
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button) findViewById(R.id.uploadButton);
messageText = (TextView) findViewById(R.id.messageText);
messageText.setText("Uploading file path :- '/mnt/sdcard/"
+ uploadFileName + "'");
/************* Php script path ****************/
upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";
uploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection connection = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
+ uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ uploadFilePath + "" + uploadFileName);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // Allow Inputs
connection.setDoOutput(true); // Allow Outputs
connection.setUseCaches(false); // Don't use a Cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
// dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
// + fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ URLEncoder.encode(fileName, "UTF-8") + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " http://www.androidexample.com/media/uploads/"
+ uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
PHP File
<?php
$target_path = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else {
echo "There was an error uploading the file, please try again!";
}
?>
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 can use jquery-disablescroll to solve the problem:
$window.disablescroll();
$window.disablescroll("undo");
Supports handleWheel
, handleScrollbar
, handleKeys
and scrollEventKeys
.
Start Android Studio. Close any open project.Go to File > Close Project.(Welcome window will open) Go to Configure > Settings. On Settings dialog,select Compiler (Gradle-based Android Projects) from left and set VM Options to -Xmx512m(i.e. write -Xmx512m under VM Options:) and press OK.
and then do this
Right click on My Computer and Open up your System Properties (The bit you had open before that shows your CPU/RAM values) >> On the left sidebar, click Advanced System Settings >> Click Environment Variables >> Under System Variables, press New >> Use the values below: // Variable name: _JAVA_OPTIONS // Variable value: -Xmx524M then, press OK and try again. restart Android Studio
using Range with
[Range(typeof(Decimal), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]
[Range(typeof(Decimal),"0.0", "1000000000000000000"]
Hope it will help
You can use the following flags --single-branch
&& --depth
to download the specific branch and to limit the amount of history which will be downloaded.
You will clone the repo from a certain point in time and only for the given branch
git clone -b <branch> --single-branch <url> --depth <number of commits>
--[no-]single-branch
Clone only the history leading to the tip of a single branch, either specified by the
--branch
option or the primary branch remote’sHEAD
points at.Further fetches into the resulting repository will only update the
remote-tracking
branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when--single-branch
clone was made, no remote-tracking branch is created.
--depth
Create a shallow clone with a history truncated to the specified number of commits
Make sure Anonymous access is enabled on IIS -> Authentication.
But also right click on it, then click on Edit, and choose a domain\username and password. (With access to the physical folder of the application).
I find it more convenient to use something like the following:
document.querySelector('*').addEventListener('click',function(event){
if( event.target.tagName != "IMG"){
return;
}
// HANDLE CLICK ON IMAGES HERE
});
I would say to set up the font size change in your CSS stylesheet file.
I'm pretty sure that you want all text at the same size for all your form fields. Adding inline styles in your HTML will add to many lines at the end... plus you would need to add it to the other types of form fields such as <select>
.
HTML:
<div id="cForm">
<form method="post">
<input type="text" name="name" placeholder="Name" data-required="true">
<option value="" selected="selected" >Choose Category...</option>
</form>
</div>
CSS:
input, select {
font-size: 18px;
}
It seems the new Bootstrap version adds a margin-right: -100%
to each item, therefore in the responsive solution given in the most upvoted answer in here, this property should be reset, e.g.:
.carousel-inner .carousel-item {
margin-right: inherit;
}
A working codepen with v4.3.1 in LESS.
Sharding does more than just horizontal partitioning. According to the wikipedia article,
Horizontal partitioning splits one or more tables by row, usually within a single instance of a schema and a database server. It may offer an advantage by reducing index size (and thus search effort) provided that there is some obvious, robust, implicit way to identify in which partition a particular row will be found, without first needing to search the index, e.g., the classic example of the 'CustomersEast' and 'CustomersWest' tables, where their zip code already indicates where they will be found.
Sharding goes beyond this: it partitions the problematic table(s) in the same way, but it does this across potentially multiple instances of the schema. The obvious advantage would be that search load for the large partitioned table can now be split across multiple servers (logical or physical), not just multiple indexes on the same logical server.
Also,
Splitting shards across multiple isolated instances requires more than simple horizontal partitioning. The hoped-for gains in efficiency would be lost, if querying the database required both instances to be queried, just to retrieve a simple dimension table. Beyond partitioning, sharding thus splits large partitionable tables across the servers, while smaller tables are replicated as complete units
I was following along the Vue documentation at https://vuejs.org/v2/guide/index.html when I ran into this issue.
Later they clarify the syntax:
So far, we’ve only registered components globally, using Vue.component:
Vue.component('my-component-name', { // ... options ... })
Globally registered components can be used in the template of any root Vue instance (new Vue) created afterwards – and even inside all >subcomponents of that Vue instance’s component tree.
(https://vuejs.org/v2/guide/components.html#Organizing-Components)
So as Umesh Kadam says above, just make sure the global component definition comes before the var app = new Vue({})
instantiation.
To answer more precisely to the question:
conda (which is conda for miniconda as for Anaconda) updates all but ONLY within a specific version of a package -> major and minor. That's the paradigm.
In the documentation you will find "NOTE: Conda updates to the highest version in its series, so Python 2.7 updates to the highest available in the 2.x series and 3.6 updates to the highest available in the 3.x series." doc
If Wang does not gives a reproducible example, one can only assist. e.g. is it really the virtual environment he wants to update or could Wang get what he/she wants with
conda update -n ENVIRONMENT --all
*PLEASE read the docs before executing "update --all"! This does not lead to an update of all packages by nature. Because conda tries to resolve the relationship of dependencies between all packages in your environment, this can lead to DOWNGRADED packages without warnings.
If you only want to update almost all, you can create a pin file
echo "conda ==4.0.0" >> ~/miniconda3/envs/py35/conda-meta/pinned
echo "numpy 1.7.*" >> ~/miniconda3/envs/py35/conda-meta/pinned
before running the update. conda issues not pinned
If later on you want to ignore the file in your env for an update, you can do:
conda update --all --no-pin
You should not do update --all. If you need it nevertheless you are saver to test this in a cloned environment.
First step should always be to backup your current specification:
conda list -n py35 --explicit
(but even so there is not always a link to the source available - like for jupyterlab extensions)
Next you can clone and update:
conda create -n py356 --clone py35
conda activate py356
conda config --set pip_interop_enabled True # for conda>=4.6
conda update --all
update:
Because the idea of conda is nice but it is not working out very well for complex environments I personally prefer the combination of nix-shell
(or lorri
) and poetry
[as superior pip/conda .-)] (intro poetry2nix).
Alternatively you can use nix
and mach-nix
(where you only need you requirements file. It resolves and builds environments best.
On Linux / macOS you could use nix like
nix-env -iA nixpkgs.python37
to enter an environment that has e.g. in this case Python3.7 (for sure you can change the version)
or as a very good Python (advanced) environment you can use mach-nix (with nix) like
mach-nix env ./env -r requirements.txt
(which even supports conda [but currently in beta])
or via api like
nix-shell -p nixFlakes --run "nix run github:davhau/mach-nix#with.ipython.pandas.seaborn.bokeh.scikit-learn "
Finally if you really need to work with packages that are not compatible due to its dependencies, it is possible with technologies like NixOS/nix-pkgs.
Only this worked for me:
$(document).ready(function(){
$('select').not('.disabled').formSelect();
});
try this:
<input type="button" onClick="document.getElementById('middle').scrollIntoView();" />
// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);
// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself
// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);
Another Solution to isolate a character in a string
package main
import "fmt"
func main() {
var word string = "ZbjTS"
// P R I N T
fmt.Println(word)
yo := string([]rune(word)[0])
fmt.Println(yo)
//I N D E X
x :=0
for x < len(word){
yo := string([]rune(word)[x])
fmt.Println(yo)
x+=1
}
}
for string arrays also:
fmt.Println(string([]rune(sArray[0])[0]))
// = commented line
let the_string = "Swift"
let resultString = "\(the_string) is a new Programming Language"
You can use the readline module to read from stdin line by line:
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
console.log(line);
})
Something like gunzip using the -r flag?....
Travel the directory structure recursively. If any of the file names specified on the command line are directories, gzip will descend into the directory and compress all the files it finds there (or decompress them in the case of gunzip ).
Here's a yet another solution to your problem:
def to_bool(s):
return 1 - sum(map(ord, s)) % 2
# return 1 - sum(s.encode('ascii')) % 2 # Alternative for Python 3
It works because the sum of the ASCII codes of 'true'
is 448
, which is even, while the sum of the ASCII codes of 'false'
is 523
which is odd.
The funny thing about this solution is that its result is pretty random if the input is not one of 'true'
or 'false'
. Half of the time it will return 0
, and the other half 1
. The variant using encode
will raise an encoding error if the input is not ASCII (thus increasing the undefined-ness of the behaviour).
Seriously, I believe the most readable, and faster, solution is to use an if
:
def to_bool(s):
return 1 if s == 'true' else 0
See some microbenchmarks:
In [14]: def most_readable(s):
...: return 1 if s == 'true' else 0
In [15]: def int_cast(s):
...: return int(s == 'true')
In [16]: def str2bool(s):
...: try:
...: return ['false', 'true'].index(s)
...: except (ValueError, AttributeError):
...: raise ValueError()
In [17]: def str2bool2(s):
...: try:
...: return ('false', 'true').index(s)
...: except (ValueError, AttributeError):
...: raise ValueError()
In [18]: def to_bool(s):
...: return 1 - sum(s.encode('ascii')) % 2
In [19]: %timeit most_readable('true')
10000000 loops, best of 3: 112 ns per loop
In [20]: %timeit most_readable('false')
10000000 loops, best of 3: 109 ns per loop
In [21]: %timeit int_cast('true')
1000000 loops, best of 3: 259 ns per loop
In [22]: %timeit int_cast('false')
1000000 loops, best of 3: 262 ns per loop
In [23]: %timeit str2bool('true')
1000000 loops, best of 3: 343 ns per loop
In [24]: %timeit str2bool('false')
1000000 loops, best of 3: 325 ns per loop
In [25]: %timeit str2bool2('true')
1000000 loops, best of 3: 295 ns per loop
In [26]: %timeit str2bool2('false')
1000000 loops, best of 3: 277 ns per loop
In [27]: %timeit to_bool('true')
1000000 loops, best of 3: 607 ns per loop
In [28]: %timeit to_bool('false')
1000000 loops, best of 3: 612 ns per loop
Notice how the if
solution is at least 2.5x times faster than all the other solutions. It does not make sense to put as a requirement to avoid using if
s except if this is some kind of homework (in which case you shouldn't have asked this in the first place).
The only property corresponding in WPF to the
Winforms property: TextBox.Multiline = true
is the WPF property: TextBox.AcceptsReturn = true
.
<TextBox AcceptsReturn="True" ...... />
All other settings, such as VerticalAlignement
, WordWrap
etc., only control how the TextBox interacts in the UI but do not affect the Multiline
behaviour.
if you wanna ng-model value, if you can write like this in the triggered event: $scope.searchText
Once I used double slash while calling the API then I got the same error.
I had to call http://localhost:8080/getSomething but I did Like http://localhost:8080//getSomething. I resolved it by removing extra slash.
from tkinter import *
from tkinter import messagebox
root = Tk()
root.geometry("400x400")
root.resizable(0, 0)
root.title("Timer")
seconds = 21
def timer():
global seconds
if seconds > 0:
seconds = seconds - 1
mins = seconds // 60
m = str(mins)
if mins < 10:
m = '0' + str(mins)
se = seconds - (mins * 60)
s = str(se)
if se < 10:
s = '0' + str(se)
time.set(m + ':' + s)
timer_display.config(textvariable=time)
# call this function again in 1,000 milliseconds
root.after(1000, timer)
elif seconds == 0:
messagebox.showinfo('Message', 'Time is completed')
root.quit()
frames = Frame(root, width=500, height=500)
frames.pack()
time = StringVar()
timer_display = Label(root, font=('Trebuchet MS', 30, 'bold'))
timer_display.place(x=145, y=100)
timer() # start the timer
root.mainloop()
foreach($images as $key=>$image)
{
if($image == 'http://i27.tinypic.com/29ykt1f.gif' ||
$image == 'http://img3.abload.de/img/10nxjl0fhco.gif' ||
$image == 'http://i42.tinypic.com/9pp2tx.gif')
{ unset($images[$key]); }
}
!!foreach($images as $key=>$image
cause $image is the value, so $images[$image] make no sense.
In my case, I wanted to check out
a new branch
that has cut recently
but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network
so I copped the previous branch
that I already checked in
I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help
)
svn switch ^/branches/newBranchName
go check svn info
again you can see it is becoming the newBranchName go ahead and svn up
and this how I got the new branch easily, quickly with minimum data transmitting over the internet
hope sharing my case helps and speeds up your work
for all databases:
mysqlcheck -Aos -uuser -p
For one Database optimization:
mysqlcheck -os -uroot -p dbtest3
For Office 365 users or Hybrid exchange, go to using Internet Explorer or Edge, go to the exchange admin center, choose hybrid, setup, chose the right button for hybrid or exchange online.
To connect:
Connect-EXOPSSession
To see the relevant mailboxes:
Get-mailbox -filter {ExchangeUserAccountControl -eq 'AccountDisabled' -and RecipientType -eq 'UserMailbox' -and RecipientTypeDetails -ne 'SharedMailbox' }
To block based on the above idea of 0KB size:
Get-mailbox -filter {ExchangeUserAccountControl -eq 'AccountDisabled' -and RecipientTypeDetails -ne 'SharedMailbox' -and RecipientType -eq 'UserMailbox' } | Set-Mailbox -MaxReceiveSize 0KB -HiddenFromAddressListsEnabled $true
Excel does not have any way to do this.
The result of a formula in a cell in Excel must be a number, text, logical (boolean) or error. There is no formula cell value type of "empty" or "blank".
One practice that I have seen followed is to use NA() and ISNA(), but that may or may not really solve your issue since there is a big differrence in the way NA() is treated by other functions (SUM(NA()) is #N/A while SUM(A1) is 0 if A1 is empty).
I tried in my angular7 project by writing these lines and worked.
<link rel="icon" type="image/x-icon" href="filepath/filename.ico">
please be noted that the image file should be in icon format (.ico)
You can use Replace instead of INSERT ... ON DUPLICATE KEY UPDATE.
Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;
<select name="foo" id="foo" value="${myBean.foo}">
<option value="">ALL</option>
<c:forEach items="${fooList}" var="val">
<option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>
</c:forEach>
</select>
You can use the Enumerable.Where extension method:
var matches = myList.Where(p => p.Name == nameToExtract);
Returns an IEnumerable<SampleClass>
. Assuming you want a filtered List
, simply call .ToList()
on the above.
By the way, if I were writing the code above today, I'd do the equality check differently, given the complexities of Unicode string handling:
var matches = myList.Where(p => String.Equals(p.Name, nameToExtract, StringComparison.CurrentCulture));
A demonstration of lazy
- as defined above - execution when defined vs execution when accessed: (using 2.12.7 scala shell)
// compiler says this is ok when it is lazy
scala> lazy val t: Int = t
t: Int = <lazy>
//however when executed, t recursively calls itself, and causes a StackOverflowError
scala> t
java.lang.StackOverflowError
...
// when the t is initialized to itself un-lazily, the compiler warns you of the recursive call
scala> val t: Int = t
<console>:12: warning: value t does nothing other than call itself recursively
val t: Int = t
This answer will do what you need, although usually you don't add specific usernames to sudoers
. Instead, you have a group of sudoers and just add your user to that group when needed. This way you don't need to use visudo
more than once when giving sudo
permission to users.
If you're on Ubuntu, the group is most probably already set up and called admin
:
$ sudo cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
...
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
# See sudoers(5) for more information on "#include" directives:
#includedir /etc/sudoers.d
On other distributions, like Arch and some others, it's usually called wheel
and you may need to set it up: Arch Wiki
To give users in the wheel group full root privileges when they precede a command with "sudo", uncomment the following line: %wheel ALL=(ALL) ALL
Also note that on most systems visudo
will read the EDITOR
environment variable or default to using vi
. So you can try to do EDITOR=vim visudo
to use vim
as the editor.
To add a user to the group you should run (as root):
# usermod -a -G groupname username
where groupname
is your group (say, admin
or wheel
) and username
is the username (say, john
).
C-x C-e ;; current line
M-x eval-region ;; region
M-x eval-buffer ;; whole buffer
M-x load-file ~/.emacs.d/init.el
Lexical scope refers to the lexicon of identifiers (e.g., variables, functions, etc.) visible from the current position in the execution stack.
- global execution context
- foo
- bar
- function1 execution context
- foo2
- bar2
- function2 execution context
- foo3
- bar3
foo
and bar
are always within the lexicon of available identifiers because they are global.
When function1
is executed, it has access to a lexicon of foo2
, bar2
, foo
, and bar
.
When function2
is executed, it has access to a lexicon of foo3
, bar3
, foo2
, bar2
, foo
, and bar
.
The reason global and/or outer functions do not have access to an inner functions identifiers is because the execution of that function has not occurred yet and therefore, none of its identifiers have been allocated to memory. What’s more, once that inner context executes, it is removed from the execution stack, meaning that all of it’s identifiers have been garbage collected and are no longer available.
Finally, this is why a nested execution context can ALWAYS access it’s ancestors execution context and thus why it has access to a greater lexicon of identifiers.
See:
Special thanks to @robr3rd for help simplifying the above definition.
I think this is actually what you're looking for:
.my_container ul
{
list-style: initial;
margin: initial;
padding: 0 0 0 40px;
}
.my_container li
{
display: list-item;
}
You can use text property in your xml file for particular Edittext fields. For example :
<EditText
android:id="@+id/ET_User"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yourusername"/>
like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.
In Another way just you get the particular Edittext field id in activity class and set text to that one.
Another way = programmatically
Example:
EditText username=(EditText)findViewById(R.id.ET_User);
username.setText("jack");
There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.
You can check if a variable is defined:
if [ -z "$a" ]
then
echo "not defined"
else
echo "defined"
fi
and then set a default value for undefined variables or do something else.
The -z
checks for a zero-length (i.e. empty) string. See man bash
and look for the CONDITIONAL EXPRESSIONS section.
You can also use set -u
at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.
Did they add a runtime List<> and/or Map<> type class to typepad 1.0
No, providing a runtime is not the focus of the TypeScript team.
is there a solid library out there someone wrote that provides this functionality?
I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections
JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts
: https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want
The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.
As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:
/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml
The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.
BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is
@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
public void bussinesMethod(){
}
}
No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.
Now in your client code you need to lookup "MyComponentName".
Reflection can help you.
var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
You just need to add @JoinColumn(name="column_name")
to Host Entity relation . column_name is the database column name in person table.
@Entity
public class Person {
@Id
public int id;
@OneToOne
@JoinColumn(name="other_info")
public OtherInfo otherInfo;
rest of attributes ...
}
Person has a one-to-one relationship with OtherInfo: mappedBy="var_name" var_name is variable name for otherInfo in Person class.
@Entity
public class OtherInfo {
@Id
@OneToOne(mappedBy="otherInfo")
public Person person;
rest of attributes ...
}
This is a simple Python script that does just what you need:
#!/usr/bin/python
import sys
# Clipboard storage
clipboard_file = '/tmp/clipboard.tmp'
if(sys.stdin.isatty()): # Should write clipboard contents out to stdout
with open(clipboard_file, 'r') as c:
sys.stdout.write(c.read())
elif(sys.stdout.isatty()): # Should save stdin to clipboard
with open(clipboard_file, 'w') as c:
c.write(sys.stdin.read())
Save this as an executable somewhere in your path (I saved it to /usr/local/bin/clip
. You can pipe in stuff to be saved to your clipboard...
echo "Hello World" | clip
And you can pipe what's in your clipboard to some other program...
clip | cowsay
_____________
< Hello World >
-------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
Running it by itself will simply output what's in the clipboard.
For me the same exception was thrown when the toString was defined as such:
@Override
public String toString() {
return "ListElem [next=" + next + ", data=" + data + "]";
}
Where ListElem
is a linked list element and I created a ListElem
as such:
private ListElem<Integer> cyclicLinkedList = new ListElem<>(3);
ListElem<Integer> cyclicObj = new ListElem<>(4);
...
cyclicLinkedList.setNext(new ListElem<Integer>(2)).setNext(cyclicObj)
.setNext(new ListElem<Integer>(6)).setNext(new ListElem<Integer>(2)).setNext(cyclicObj);
This effectively caused a cyclic linked list that cannot be printed. Thanks for the pointer.
With 500k documents, there is no reason to scale whatsoever. A typical laptop with an SSD and 8GB of ram can easily do 10s of millions of records, so if you are trying to pick because of scaling your choice doesn't really matter. I would suggest you pick what you like the most, and perhaps where you can find the most online support with.
I get get the same minicom error, "cannot open /dev/ttyUSB0: No such file or directory"
Three notes:
I get the error when the device attached to the serial port end of my Prolific Technology PL2303 USB/Serial adapter is turned off. After turning on the device (an embedded controller running Linux) minicom connected fine.
I have to run as super user (i.e. sudo minicom
)
Sometimes I have to unplug and plug back in the USB-to-serial adapter to get minicom to connect to it.
I am running Ubuntu 10.04 LTS (Lucid Lynx) under VMware (running on Windows 7). In this situation, make sure the device is attached to VM operating system by right clicking on the USB/Serial USB icon in the lower right of the VMware window and select Connect (Disconnect from Host).
Remember to press Ctrl + A to get minicom's prompt, and type X to exit the program. Just exiting the terminal session running minicom will leave the process running.
Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded
: this specifies +
for spaces.
URLs are encoded as RFC 1738 which specifies %20
.
In theory I think you should have %20 before the ?
and + after:
example.com/foo%20bar?foo+bar
Don't use spaces...
(Incorrect)
SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'
(Correct)
SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'
Write a:hover::before
instead of a::before:hover
: example.
If you actually want Yes and No buttons (and assuming WinForms):
void button_Click(object sender, EventArgs e)
{
var message = "Yes or No?";
var title = "Hey!";
var result = MessageBox.Show(
message, // the message to show
title, // the title for the dialog box
MessageBoxButtons.YesNo, // show two buttons: Yes and No
MessageBoxIcon.Question); // show a question mark icon
// the following can be handled as if/else statements as well
switch (result)
{
case DialogResult.Yes: // Yes button pressed
MessageBox.Show("You pressed Yes!");
break;
case DialogResult.No: // No button pressed
MessageBox.Show("You pressed No!");
break;
default: // Neither Yes nor No pressed (just in case)
MessageBox.Show("What did you press?");
break;
}
}
Here's a wrapper to pretty-fy it if you need it:
(function() {
var originalSetInterval = window.setInterval;
window.setInterval = function(fn, delay, runImmediately) {
if(runImmediately) fn();
return originalSetInterval(fn, delay);
};
})();
Set the third argument of setInterval to true and it'll run for the first time immediately after calling setInterval:
setInterval(function() { console.log("hello world"); }, 5000, true);
Or omit the third argument and it will retain its original behaviour:
setInterval(function() { console.log("hello world"); }, 5000);
Some browsers support additional arguments for setInterval which this wrapper doesn't take into account; I think these are rarely used, but keep that in mind if you do need them.
I took @jaytrixz's answer/comment one step further and added "text/html" to the existing set of types. That way when they fix it on the server side to "application/json" or "text/json" I claim it'll work seamlessly.
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
I believe this is what you are looking for:
Indexers (C# Programming Guide)
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get => arr[i];
set => arr[i] = value;
}
}
// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection =
new SampleCollection<string>();
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.
I had the same issue
Just make sure that you have the latest versions of all the dependencies. I used the current versions for Firebase core and auth. The newer versions have bug fixes.
You can get the latest versions from here : https://firebase.google.com/support/release-notes/android
Using the latest version at current point of time:
in app/build.gradle :
dependencies {
implementation 'com.google.firebase:firebase-core:16.0.6'
implementation 'com.google.firebase:firebase-auth:16.1.0'
}
Datanewolf's code is ALMOST right. I had to reverse both the winding and the normals to make it work properly with the fixed pipeline. The below works correctly with cull on or off for me:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
int r, s;
vertices.resize(rings * sectors * 3);
normals.resize(rings * sectors * 3);
texcoords.resize(rings * sectors * 2);
std::vector<GLfloat>::iterator v = vertices.begin();
std::vector<GLfloat>::iterator n = normals.begin();
std::vector<GLfloat>::iterator t = texcoords.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
*t++ = s*S;
*t++ = r*R;
*v++ = x * radius;
*v++ = y * radius;
*v++ = z * radius;
*n++ = -x;
*n++ = -y;
*n++ = -z;
}
indices.resize(rings * sectors * 4);
std::vector<GLushort>::iterator i = indices.begin();
for(r = 0; r < rings-1; r++)
for(s = 0; s < sectors-1; s++) {
/*
*i++ = r * sectors + s;
*i++ = r * sectors + (s+1);
*i++ = (r+1) * sectors + (s+1);
*i++ = (r+1) * sectors + s;
*/
*i++ = (r+1) * sectors + s;
*i++ = (r+1) * sectors + (s+1);
*i++ = r * sectors + (s+1);
*i++ = r * sectors + s;
}
Edit: There was a question on how to draw this... in my code I encapsulate these values in a G3DModel class. This is my code to setup the frame, draw the model, and end it:
void GraphicsProvider3DPriv::BeginFrame()const{
int win_width;
int win_height;// framework of choice here
glfwGetWindowSize(window, &win_width, &win_height); // retrieve window
float const win_aspect = (float)win_width / (float)win_height;
// set lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
GLfloat lightpos[] = {0, 0.0, 0, 0.};
glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
GLfloat lmodel_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
// set up world transform
glClearColor(0.f, 0.f, 0.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT|GL_ACCUM_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
}
void GraphicsProvider3DPriv::DrawModel(const G3DModel* model, const Transform3D transform)const{
G3DModelPriv* privModel = (G3DModelPriv *)model;
glPushMatrix();
glLoadMatrixf(transform.GetOGLData());
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &privModel->vertices[0]);
glNormalPointer(GL_FLOAT, 0, &privModel->normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &privModel->texcoords[0]);
glEnable(GL_TEXTURE_2D);
//glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, privModel->texname);
glDrawElements(GL_QUADS, privModel->indices.size(), GL_UNSIGNED_SHORT, &privModel->indices[0]);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
void GraphicsProvider3DPriv::EndFrame()const{
/* Swap front and back buffers */
glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);
glDisable(GL_CULL_FACE);
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
If your intention was to find a way to represent null in an enumeration of singleton objects, then it's a bad idea to (de)reference null (it C++11, nullptr).
Why not declare static singleton object that represents NULL within the class as follows and add a cast-to-pointer operator that returns nullptr ?
Edit: Corrected several mistypes and added if-statement in main() to test for the cast-to-pointer operator actually working (which I forgot to.. my bad) - March 10 2015 -
// Error.h
class Error {
public:
static Error& NOT_FOUND;
static Error& UNKNOWN;
static Error& NONE; // singleton object that represents null
public:
static vector<shared_ptr<Error>> _instances;
static Error& NewInstance(const string& name, bool isNull = false);
private:
bool _isNull;
Error(const string& name, bool isNull = false) : _name(name), _isNull(isNull) {};
Error() {};
Error(const Error& src) {};
Error& operator=(const Error& src) {};
public:
operator Error*() { return _isNull ? nullptr : this; }
};
// Error.cpp
vector<shared_ptr<Error>> Error::_instances;
Error& Error::NewInstance(const string& name, bool isNull = false)
{
shared_ptr<Error> pNewInst(new Error(name, isNull)).
Error::_instances.push_back(pNewInst);
return *pNewInst.get();
}
Error& Error::NOT_FOUND = Error::NewInstance("NOT_FOUND");
//Error& Error::NOT_FOUND = Error::NewInstance("UNKNOWN"); Edit: fixed
//Error& Error::NOT_FOUND = Error::NewInstance("NONE", true); Edit: fixed
Error& Error::UNKNOWN = Error::NewInstance("UNKNOWN");
Error& Error::NONE = Error::NewInstance("NONE");
// Main.cpp
#include "Error.h"
Error& getError() {
return Error::UNKNOWN;
}
// Edit: To see the overload of "Error*()" in Error.h actually working
Error& getErrorNone() {
return Error::NONE;
}
int main(void) {
if(getError() != Error::NONE) {
return EXIT_FAILURE;
}
// Edit: To see the overload of "Error*()" in Error.h actually working
if(getErrorNone() != nullptr) {
return EXIT_FAILURE;
}
}
startService(new Intent(this, MyService.class));
Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
...
<service
android:name=".MyService"
android:label="My Service" >
</service>
</application>
sys.path
. See site
module.A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/
In a nutshell:
An imperative language specfies a series of instructions that the computer executes in sequence (do this, then do that).
A declarative language declares a set of rules about what outputs should result from which inputs (eg. if you have A, then the result is B). An engine will apply these rules to inputs, and give an output.
A functional language declares a set of mathematical/logical functions which define how input is translated to output. eg. f(y) = y * y. it is a type of declarative language.
The following definition might be more efficient than the first solution proposed
def new_list_from_intervals(original_list, *intervals):
n = sum(j - i for i, j in intervals)
new_list = [None] * n
index = 0
for i, j in intervals :
for k in range(i, j) :
new_list[index] = original_list[k]
index += 1
return new_list
then you can use it like below
new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))
Change the Border Color back to Grey
.btn:focus,
.btn:active{
border: 1px solid #ced4da !important;
}
One doesn't always know the type into which to deserialize. So it would be handy to be able to take any JSON (that contains some array) and dynamically produce a table from that.
An issue can arise however, where the deserializer doesn't know where to look for the array to tabulate. When this happens, we get an error message similar to the following:
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.
Even if we give it come encouragement or prepare our json accordingly, then "object" types within the array can still prevent tabulation from occurring, where the deserializer doesn't know how to represent the objects in terms of rows, etc. In this case, errors similar to the following occur:
Unexpected JSON token when reading DataTable: StartObject. Path '[0].__metadata', line 3, position 19.
The below example JSON includes both of these problematic features:
{
"results":
[
{
"Enabled": true,
"Id": 106,
"Name": "item 1",
},
{
"Enabled": false,
"Id": 107,
"Name": "item 2",
"__metadata": { "Id": 4013 }
}
]
}
So how can we resolve this, and still maintain the flexibility of not knowing the type into which to derialize?
Well here is a simple approach I came up with (assuming you are happy to ignore the object-type properties, such as __metadata in the above example):
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Linq;
...
public static DataTable Tabulate(string json)
{
var jsonLinq = JObject.Parse(json);
// Find the first array using Linq
var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
var trgArray = new JArray();
foreach (JObject row in srcArray.Children<JObject>())
{
var cleanRow = new JObject();
foreach (JProperty column in row.Properties())
{
// Only include JValue types
if (column.Value is JValue)
{
cleanRow.Add(column.Name, column.Value);
}
}
trgArray.Add(cleanRow);
}
return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());
}
I know this could be more "LINQy" and has absolutely zero exception handling, but hopefully the concept is conveyed.
We're starting to use more and more services at my work that spit back JSON, so freeing ourselves of strongly-typing everything, is my obvious preference because I'm lazy!
Check that you don't have a .my.cnf hiding in your homedir. That was my problem.
I think the parent Container needs to be given a maxWidth of the proper size. It looks like the Text box will fill whatever space it is given above.
Try to make new instance like i did below
var common_axios = axios.create({
baseURL: 'https://sample.com'
});
// Set default headers to common_axios ( as Instance )
common_axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// Check your Header
console.log(common_axios.defaults.headers);
How to Use it
common_axios.get(url).......
common_axios.post(url).......
You can use sed
for this. For example:
$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...
The -n
switch tells sed to not output each line of the file it reads (default behaviour).
The last p
after the regular expressions tells it to print lines that match the preceding expression.
The expression '/pattern1/,/pattern2/'
will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55
and the string Feb 23 14:00
.
Just adding a little more info.
JPA manages the version under the hood for you, however it doesn't do so when you update your record via JPAUpdateClause
, in such cases you need to manually add the version increment to the query.
Same can be said about updating via JPQL, i.e. not a simple change to the entity, but an update command to the database even if that is done by hibernate
Pedro
Three types of commenting are supported
Hash base single line commenting using #
Select * from users ; # this will list users
Select * from users ; -- this will list users
Note : Its important to have single white space just after --
3) Multi line commenting using /* */
Select * from users ; /* this will list users */
Pass using JSON
<a routerLink = "/link"
[queryParams] = "{parameterName: objectToPass| json }">
sample Link
</a>
Try adding these after <Playlist>
<AutoLoad>false</AutoLoad>
<AutoPlay>false</AutoPlay>
Yes, just format your strings in the standard String.format()
way.
See the method Context.getString(int, Object...)
and the Android or Java Formatter
documentation.
In your case, the string definition would be:
<string name="timeFormat">%1$d minutes ago</string>
The top answer [[ $b = 5 ]] && a="$c" || a="$d"
should only be used if you are certain there will be no error after the &&
, otherwise it will incorrectly excute the part after the ||
.
To solve that problem I wrote a ternary function that behaves as it should and it even uses the ?
and :
operators:
Edit - new solution
Here is my new solution that does not use $IFS
nor ev(a/i)l
.
function executeCmds()
{
declare s s1 s2 i j k
declare -A cmdParts
declare pIFS=$IFS
IFS=$'\n'
declare results=($(echo "$1" | grep -oP '{ .*? }'))
IFS=$pIFS
s="$1"
for ((i=0; i < ${#results[@]}; i++)); do
s="${s/${results[$i]}/'\0'}"
results[$i]="${results[$i]:2:${#results[$i]}-3}"
results[$i]=$(echo ${results[$i]%%";"*})
done
s="$s&&"
let cmdParts[t]=0
while :; do
i=${cmdParts[t]}
let cmdParts[$i,t]=0
s1="${s%%"&&"*}||"
while :; do
j=${cmdParts[$i,t]}
let cmdParts[$i,$j,t]=0
s2="${s1%%"||"*};"
while :; do
cmdParts[$i,$j,${cmdParts[$i,$j,t]}]=$(echo ${s2%%";"*})
s2=${s2#*";"}
let cmdParts[$i,$j,t]++
[[ $s2 ]] && continue
break
done
s1=${s1#*"||"}
let cmdParts[$i,t]++
[[ $s1 ]] && continue
break
done
let cmdParts[t]++
s=${s#*"&&"}
[[ $s ]] && continue
break
done
declare lastError=0
declare skipNext=false
for ((i=0; i < ${cmdParts[t]}; i++ )) ; do
let j=0
while :; do
let k=0
while :; do
if $skipNext; then
skipNext=false
else
if [[ "${cmdParts[$i,$j,$k]}" == "\0" ]]; then
executeCmds "${results[0]}" && lastError=0 || lastError=1
results=("${results[@]:1}")
elif [[ "${cmdParts[$i,$j,$k]:0:1}" == "!" || "${cmdParts[$i,$j,$k]:0:1}" == "-" ]]; then
[ ${cmdParts[$i,$j,$k]} ] && lastError=0 || lastError=1
else
${cmdParts[$i,$j,$k]}
lastError=$?
fi
if (( k+1 < cmdParts[$i,$j,t] )); then
skipNext=false
elif (( j+1 < cmdParts[$i,t] )); then
(( lastError==0 )) && skipNext=true || skipNext=false
elif (( i+1 < cmdParts[t] )); then
(( lastError==0 )) && skipNext=false || skipNext=true
fi
fi
let k++
[[ $k<${cmdParts[$i,$j,t]} ]] || break
done
let j++
[[ $j<${cmdParts[$i,t]} ]] || break
done
done
return $lastError
}
function t()
{
declare commands="$@"
find="$(echo ?)"
replace='?'
commands="${commands/$find/$replace}"
readarray -d '?' -t statement <<< "$commands"
condition=${statement[0]}
readarray -d ':' -t statement <<< "${statement[1]}"
success="${statement[0]}"
failure="${statement[1]}"
executeCmds "$condition" || { executeCmds "$failure"; return; }
executeCmds "$success"
}
executeCmds
separates each command individually, apart from the ones that should be skipped due to the &&
and ||
operators. It uses []
whenever a command starts with !
or a flag.
There are two ways to pass commands to it:
;
, &&
, and ||
operators.t ls / ? ls qqq '||' echo aaa : echo bbb '&&' ls qq
t 'ls /a ? ls qqq || echo aaa : echo bbb && ls qq'
NB I found no way to pass in &&
and ||
operators as parameters unquoted, as they are illegal characters for function names and aliases, and I found no way to override bash operators.
Old solution - uses ev(a/i)l
function t()
{
pIFS=$IFS
IFS="?"
read condition success <<< "$@"
IFS=":"
read success failure <<< "$success"
IFS=$pIFS
eval "$condition" || { eval "$failure" ; return; }
eval "$success"
}
t ls / ? ls qqq '||' echo aaa : echo bbb '&&' ls qq
t 'ls /a ? ls qqq || echo aaa : echo bbb && ls qq'
As final note the Mozilla documentation explicitly says that
The above example would fail if the header was wildcarded as: Access-Control-Allow-Origin: *. Since the Access-Control-Allow-Origin explicitly mentions http://foo.example, the credential-cognizant content is returned to the invoking web content.
As consequence is a not simply a bad practice to use '*'. Simply does not work :)
You are looking for git merge-base
. Usage:
$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
Did you try WKHTMLTOPDF?
It's a simple shell utility, an open source implementation of WebKit. Both are free.
We've set a small tutorial here
EDIT( 2017 ):
If it was to build something today, I wouldn't go that route anymore.
But would use http://pdfkit.org/ instead.
Probably stripping it of all its nodejs dependencies, to run in the browser.
label1.Text = DateTime.Now.Month.ToString();
and
label2.Text = DateTime.Now.Year.ToString();
Java 8 Collection has a nice method called removeIf that makes things easier and safer. From the API docs:
default boolean removeIf(Predicate<? super E> filter)
Removes all of the elements of this collection that satisfy the given predicate.
Errors or runtime exceptions thrown during iteration or by the predicate
are relayed to the caller.
Interesting note:
The default implementation traverses all elements of the collection using its iterator().
Each matching element is removed using Iterator.remove().
Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:
System.Text.Json
serialiser (see below)JavaScriptSerializer
have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.Are Json.Net's days numbered? It's still used a LOT and it's still used by MS librarties. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.
A new kid on the block since writing this is System.Text.Json
which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. as below, I'd advise you to test this yourself .
I would recommend Json.Net, see example below:
List<data> _data = new List<data>();
_data.Add(new data()
{
Id = 1,
SSN = 2,
Message = "A Message"
});
string json = JsonConvert.SerializeObject(_data.ToArray());
//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);
Or the slightly more efficient version of the above code (doesn't use a string as a buffer):
//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
JsonSerializer serializer = new JsonSerializer();
//serialize object directly into file stream
serializer.Serialize(file, _data);
}
Documentation: Serialize JSON to a file
Why? Here's a feature comparison between common serialisers as well as benchmark tests .
Below is a graph of performance taken from the linked article:
This separate post, states that:
Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now) Json.Net (6.0) allocates 8 times less memory than JavaScriptSerializer
Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned
These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.
From a controller you can also return an Object/Array and it will be sent as a JSON response (including the correct HTTP headers).
public function show($id)
{
return Customer::find($id);
}
You can use the findIndex method with a callback function and its "this" parameter.
Note: old browsers don't know findIndex but a polyfill is available.
Sample code (take care that in the original question, a new object is pushed only if neither of its data is in previoulsy pushed objects):
var a=[{name:"tom", text:"tasty"}], b;
var magic=function(e) {
return ((e.name == this.name) || (e.text == this.text));
};
b={name:"tom", text:"tasty"};
if (a.findIndex(magic,b) == -1)
a.push(b); // nothing done
b={name:"tom", text:"ugly"};
if (a.findIndex(magic,b) == -1)
a.push(b); // nothing done
b={name:"bob", text:"tasty"};
if (a.findIndex(magic,b) == -1)
a.push(b); // nothing done
b={name:"bob", text:"ugly"};
if (a.findIndex(magic,b) == -1)
a.push(b); // b is pushed into a
check the round function and how does the length
argument works. It controls the behaviour of the precision of the result
You can use numpy.shape
.
import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])
Result:
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.shape(x)
(3, 2)
First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.
Create an array of Views and apply it to: container.addView(viewarr[position]);
public class Layoutes extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
Layoutes(Context context){
this.context=context;
}
int layoutes[]={R.layout.one,R.layout.two,R.layout.three};
@Override
public int getCount() {
return layoutes.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
@Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View one=layoutInflater.inflate(R.layout.one,container,false);
View two=layoutInflater.inflate(R.layout.two,container,false);
View three=layoutInflater.inflate(R.layout.three,container,false);
View viewarr[]={one,two,three};
container.addView(viewarr[position]);
return viewarr[position];
}
@Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout) object);
}
}
You can also use super-assignment.
Rather than "<-" type "<<-". The function will recursively and repeatedly search one functional level higher for an object of that name. If it can't find one, it will create one on the global level.
With ObsoleteAttribute
you can to show the deprecated method.
Obsolete attribute has three constructor:
[Obsolete]:
is a no parameter constructor and is a default using this attribute.[Obsolete(string message)]:
in this format you can getmessage
of why this method is deprecated.[Obsolete(string message, bool error)]:
in this format message is very explicit buterror
means, in compilation time, compiler must be showing error and cause to fail compiling or not.
Ok, I am not sure what are you using(MySQL, SLQ Server, Oracle, MS Access..) But you can try the code below. It work in W3School example DB. Here try this:
SELECT city, max(length(city)) FROM Customers;
If you have a large array and only want to see a subsection of the array you can type this into the watch window;
ptr+100,10
to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.
You should use States to store the value of input fields. https://facebook.github.io/react-native/docs/state.html
setState
onChangeText={(value) => this.setState({username: value})}
this.state.username
Sample code
export default class Login extends Component {
state = {
username: 'demo',
password: 'demo'
};
<Text style={Style.label}>User Name</Text>
<TextInput
style={Style.input}
placeholder="UserName"
onChangeText={(value) => this.setState({username: value})}
value={this.state.username}
/>
<Text style={Style.label}>Password</Text>
<TextInput
style={Style.input}
placeholder="Password"
onChangeText={(value) => this.setState({password: value})}
value={this.state.password}
/>
<Button
title="LOGIN"
onPress={() =>
{
if(this.state.username.localeCompare('demo')!=0){
ToastAndroid.show('Invalid UserName',ToastAndroid.SHORT);
return;
}
if(this.state.password.localeCompare('demo')!=0){
ToastAndroid.show('Invalid Password',ToastAndroid.SHORT);
return;
}
//Handle LOGIN
}
}
/>
As of September 2016 (VSCode 1.6), this is now officially supported.
Add the following to your settings.json
file:
"editor.formatOnSave": true
What you are trying to do is not possible. The reason for this is that in a POSIX system (Linux, OSX, etc), a child process cannot modify the environment of a parent process. This includes modifying the parent process's working directory and environment variables.
When you are on the commandline and you go to execute your Node script, your current process (bash
, zsh
, whatever) spawns a new process which has it's own environment, typically a copy of your current environment (it is possible to change this via system calls; but that's beyond the scope of this reply), allowing that process to do whatever it needs to do in complete isolation. When the subprocess exits, control is handed back to your shell's process, where the environment hasn't been affected.
There are a lot of reasons for this, but for one, imagine that you executed a script in the background (via ./foo.js &
) and as it ran, it started changing your working directory or overriding your PATH
. That would be a nightmare.
If you need to perform some actions that require changing your working directory of your shell, you'll need to write a function in your shell. For example, if you're running Bash, you could put this in your ~/.bash_profile
:
do_cool_thing() {
cd "/Users"
echo "Hey, I'm in $PWD"
}
and then this cool thing is doable:
$ pwd
/Users/spike
$ do_cool_thing
Hey, I'm in /Users
$ pwd
/Users
If you need to do more complex things in addition, you could always call out to your nodejs script from that function.
This is the only way you can accomplish what you're trying to do.
For simplicity, if you do not want send a message, try this
$new_string = substr( $dynamicstring, -min( strlen( $dynamicstring ), 7 ) );
model.predict_classes(<numpy_array>)
Sample https://gist.github.com/alexcpn/0683bb940cae510cf84d5976c1652abd
Microsoft .NET framework 3.5 can be installed on windows 10 without having installation media. The file you need is called microsoft-windows-netfx3-ondemand-package.cab
. Just google it and you will get the download links.
After downloading it, copy that file to C:\dotnet35
and run the following command.
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
Tested and worked in Windows 10 without any issue.
If you want to write the history to a file:
import readline
readline.write_history_file('python_history.txt')
The help function gives:
Help on built-in function write_history_file in module readline:
write_history_file(...)
write_history_file([filename]) -> None
Save a readline history file.
The default filename is ~/.history.
Demo : http://jsfiddle.net/xavi3r/D3prt/
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
Original Answer: Resetting a multi-stage form with jQuery
Mike's suggestion (from the comments) to keep checkbox and selects intact!
Warning: If you're creating elements (so they're not in the dom), replace :hidden
with [type=hidden]
or all fields will be ignored!
$(':input','#myform')
.removeAttr('checked')
.removeAttr('selected')
.not(':button, :submit, :reset, :hidden, :radio, :checkbox')
.val('');
I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..
Opening A Seperate File:
ChDir "[Path here]" 'get into the right folder here
Workbooks.Open Filename:= "[Path here]" 'include the filename in this path
'copy data into current workbook or whatever you want here
ActiveWindow.Close 'closes out the file
Opening A File With Specified Date If It Exists:
I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.
Some common error checking statements:
On Error Resume Next 'if error occurs continues on to the next line (ignores it)
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Or (better option):
if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?
you would most likely want to use the GoTo ErrorHandler
shown below to achieve this
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
ErrorHandler:
'Display error message or any code you want to run on error here
Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm
Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/
Hope this helps!
Example on how to ensure error code doesn't run EVERYtime:
if you debug through the code without the Exit Sub
BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.
Sub Macro
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Exit Sub 'Code will exit BEFORE ErrorHandler if everything goes smoothly
'Otherwise, on error, ErrorHandler will be run
ErrorHandler:
'Display error message or any code you want to run on error here
End Sub
Also, look at this other question in you need more reference to how this works: goto block not working VBA
There are three formats with a reasonable level of support: H.264 (MPEG-4 AVC), OGG Theora (VP3) and WebM (VP8). See the wiki linked by Sam for which browsers support which; you will typically need at least one of those plus Flash fallback.
Whilst most browsers won't touch AVI, there are some browser builds that expose all the multimedia capabilities of the underlying OS to <video>
. These browser will indeed be able to play AVI, as long as they have matching codecs installed (AVI can contain about a million different video and audio formats). In particular Safari on OS X with QuickTime, or Konqi with GStreamer.
Personally I think this is an absolutely disastrous idea, as it exposes a very large codec codebase to the net, a codebase that was mostly not written to be resistant to network attacks. One of the worst drawbacks of media player plugins was the huge number of security holes they made available to every web page exploit. Let's not make this mistake again.
As mentioned before, one can use an external service like https://ident.me in order to discover the external IP address of your router.
Here is how it is done with python3
, using nothing else but the standard library:
import urllib.request
external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
print(external_ip)
The problem was the table width. I had used width: 100%
for the table. The table columns are adjusted automatically after removing the width tag.
I'd recommend always have a look at https://developers.facebook.com/tools/debug/sharing to validate your properties as Facebook often changes it's policies, compliances and API.
If you work with Messenger bots or other FB apps, you may need the property fb:app_id for link images to work in Whatsapp. More at Facebook developers webmasters site. https://developers.facebook.com/docs/sharing/webmasters
There are a set of available properties to all Maven projects.
From Introduction to the POM:
project.basedir
: The directory that the current project resides in.
This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml
file. If your POM is located inside /path/to/project/pom.xml
then this property will evaluate to /path/to/project
.
Some properties are also inherited from the Super POM, which is the case for project.build.directory
. It is the value inside the <project><build><directory>
element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory
, it is:
The directory where all files generated by the build are placed. The default value is
target
.
This is the directory that will hold every generated file by the build.
@delato468 comment must be listed as a solution as it worked for me.
In addition to defining the parameter, the user must pass it too at the time of calling the function
fetch_data(PDO $pdo, $cat_id)
In Python 3, TemporaryDirectory in the tempfile module can be used.
This is straight from the examples:
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
If you would like to keep the directory a bit longer, you could do something like this:
import tempfile
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()
The documentation also says that "On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem." So at the end of the program, for example, Python will clean up the directory if it wasn't explicitly removed. Python's unittest
may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory...
if you rely on this, though.
UPDATE user_account student, (
SELECT teacher.education_facility_id as teacherid
FROM user_account teacher
WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'
) teach SET student.student_education_facility_id= teach.teacherid WHERE student.user_type = 'ROLE_STUDENT';
MonoTouch and MonoDroid but what will happen to that part of Attachmate now is anybody's guess. Of course even with the mono solutions you're still creating non cross platform views but the idea being the reuse of business logic.
Keep an eye on http://www.xamarin.com/ it will be interesting to see what they come up with.
In C++, nested classes are not connected to any instance of the outer class. If you want bar
to access non-static members of foo
, then bar
needs to have access to an instance of foo
. Maybe something like:
class bar {
public:
int getA(foo & f ) {return foo.a;}
};
Or maybe
class bar {
private:
foo & f;
public:
bar(foo & g)
: f(g)
{
}
int getA() { return f.a; }
};
In any case, you need to explicitly make sure you have access to an instance of foo
.
This worked for me using ssh:
Settings → Developer settings → Generate new token.
git remote set-url origin https://[APPLICATION]:[NEW TOKEN]@github.com/[ORGANISATION]/[REPO].git
I had this happen repeatedly after adding images to a project in Eclipse and making them part of the build path. The solution was to right-click on the class containing the main
method, and then choose Run As -> Java Application. It seems that when you add a file to the build path, Eclipse automatically assumes that file is where the main
method is. By going through the Run As menu instead of just clicking the green Run As button, it allows you to specify the correct entry-point.
If it's a table-value function (returns a table set) you simply join it as a Table
this function generates one column table with all the values from passed comma-separated list
SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')
Checkout this out. It takes care of daylight saving , leap year as it used iOS calendar to calculate.You can change the string and conditions to includes minutes with hours and days.
+(NSString*)remaningTime:(NSDate*)startDate endDate:(NSDate*)endDate
{
NSDateComponents *components;
NSInteger days;
NSInteger hour;
NSInteger minutes;
NSString *durationString;
components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate: startDate toDate: endDate options: 0];
days = [components day];
hour = [components hour];
minutes = [components minute];
if(days>0)
{
if(days>1)
durationString=[NSString stringWithFormat:@"%d days",days];
else
durationString=[NSString stringWithFormat:@"%d day",days];
return durationString;
}
if(hour>0)
{
if(hour>1)
durationString=[NSString stringWithFormat:@"%d hours",hour];
else
durationString=[NSString stringWithFormat:@"%d hour",hour];
return durationString;
}
if(minutes>0)
{
if(minutes>1)
durationString = [NSString stringWithFormat:@"%d minutes",minutes];
else
durationString = [NSString stringWithFormat:@"%d minute",minutes];
return durationString;
}
return @"";
}
If still not works after adding MIME types, please check whether "Anonymous Authentication" is enable in Authentication section in the site and make sure to select "Application pool identity" as per the given screen shot.
In my case it helps if you don't install the x86 version over the x64 version... DOH!!!
The Application class is a singleton that you can access from any activity or anywhere else you have a Context object.
You also get a little bit of lifecycle.
You could use the Application's onCreate method to instantiate expensive, but frequently used objects like an analytics helper. Then you can access and use those objects everywhere.
If you decide to dispatch to FileServlet
then you will also need allowLinking="true"
in context.xml
in order to allow FileServlet
to traverse the symlinks.
See http://tomcat.apache.org/tomcat-6.0-doc/config/context.html
Rather than locks, I suggest you look at long-running transactions, using v$transaction
. From there you can join to v$session
, which should give you an idea about the UI (try the program and machine columns) as well as the user.