Try this sample. It works for me.
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
Produces the output at MyLogFile.log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: My first log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?
Edit:
To remove the console handler, use
logger.setUseParentHandlers(false);
since the ConsoleHandler is registered with the parent logger from which all the loggers derive.
None of the answer for me was working. Actually if you want to watch on nested data with Components being called multiple times. So they are called with different props to identify them.
For example <MyComponent chart="chart1"/> <MyComponent chart="chart2"/>
My workaround is to create an addionnal vuex state variable, that I manually update to point to the property that was last updated.
Here is a Vuex.ts implementation example:
export default new Vuex.Store({
state: {
hovEpacTduList: {}, // a json of arrays to be shared by different components,
// for example hovEpacTduList["chart1"]=[2,6,9]
hovEpacTduListChangeForChart: "chart1" // to watch for latest update,
// here to access "chart1" update
},
mutations: {
setHovEpacTduList: (state, payload) => {
state.hovEpacTduListChangeForChart = payload.chart // we will watch hovEpacTduListChangeForChart
state.hovEpacTduList[payload.chart] = payload.list // instead of hovEpacTduList, which vuex cannot watch
},
}
On any Component function to update the store:
const payload = {chart:"chart1", list: [4,6,3]}
this.$store.commit('setHovEpacTduList', payload);
Now on any Component to get the update:
computed: {
hovEpacTduListChangeForChart() {
return this.$store.state.hovEpacTduListChangeForChart;
}
},
watch: {
hovEpacTduListChangeForChart(chart) {
if (chart === this.chart) // the component was created with chart as a prop <MyComponent chart="chart1"/>
console.log("Update! for", chart, this.$store.state.hovEpacTduList[chart]);
},
},
There are some very good answers here. I'd like to add the following here as well:
some_dict = {
"foo": "bar",
"lorem": "ipsum"
}
for index, (key, value) in enumerate(some_dict.items()):
print(index, key, value)
results in
0 foo bar
1 lorem ipsum
Appears to work with Python 2.7
and 3.5
When you write your main function, you typically see one of two definitions:
int main(void)
int main(int argc, char **argv)
The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).
The arguments to main
are:
int argc
- the number of arguments passed into your program when it was run. It is at least 1
.char **argv
- this is a pointer-to-char *
. It can alternatively be this: char *argv[]
, which means 'array of char *
'. This is an array of C-style-string pointers.For example, you could do this to print out the arguments passed to your C program:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
I'm using GCC 4.5 to compile a file I called args.c
. It'll compile and build a default a.out
executable.
[birryree@lilun c_code]$ gcc -std=c99 args.c
Now run it...
[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there
So you can see that in argv
, argv[0]
is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1]
and beyond.
So basically, if you wanted a single parameter, you could say...
./myprogram integral
And you could check if argv[1]
was integral
, maybe like strcmp("integral", argv[1]) == 0
.
So in your code...
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) // no arguments were passed
{
// do something
}
if (strcmp("integral", argv[1]) == 0)
{
runIntegral(...); //or something
}
else
{
// do something else.
}
}
Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt
.
I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:
borrowed from: https://gist.github.com/gsakkis/4572159
The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:
# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime
from sqlalchemy.orm import Query
try:
basestring
except NameError:
basestring = str
def render_query(statement, dialect=None):
"""
Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement.
WARNING: This method of escaping is insecure, incomplete, and for debugging
purposes only. Executing SQL statements with inline-rendered user values is
extremely insecure.
Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
"""
if isinstance(statement, Query):
if dialect is None:
dialect = statement.session.bind.dialect
statement = statement.statement
elif dialect is None:
dialect = statement.bind.dialect
class LiteralCompiler(dialect.statement_compiler):
def visit_bindparam(self, bindparam, within_columns_clause=False,
literal_binds=False, **kwargs):
return self.render_literal_value(bindparam.value, bindparam.type)
def render_array_value(self, val, item_type):
if isinstance(val, list):
return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
return self.render_literal_value(val, item_type)
def render_literal_value(self, value, type_):
if isinstance(value, long):
return str(value)
elif isinstance(value, (basestring, date, datetime, timedelta)):
return "'%s'" % str(value).replace("'", "''")
elif isinstance(value, list):
return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
return super(LiteralCompiler, self).render_literal_value(value, type_)
return LiteralCompiler(dialect, statement).process(statement)
Tested to two levels of nested arrays.
I encountered this issue, also due to misconfiguration. I was using tomcat and in the server.xml had specified my connector as such:
<Connector port="17443" SSLEnabled="true"
protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keyAlias="wrong" keystorePass="secret"
keystoreFile="/ssl/right.jks" />
When i fixed it thusly:
<Connector port="17443" SSLEnabled="true"
protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keyAlias="right" keystorePass="secret"
keystoreFile="/ssl/right.jks" />
It worked as expected. In other words, verify that you not only have the right keystore, but that you have specified the correct alias underneath it. Thanks for the invaluable hint user396404.
More oin regards to question part 4 How do you e-mail that error to an email address? The error_log function has email destination too. http://php.net/manual/en/function.error-log.php
Agha, here I found an example that shows a usage. Send errors message via email using error_log()
error_log($this->_errorMsg, 1, ADMIN_MAIL, "Content-Type: text/html; charset=utf8\r\nFrom: ".MAIL_ERR_FROM."\r\nTo: ".ADMIN_MAIL);
Try the rename
command in the folder with the files:
rename 's/^/Unix_/' *
The argument of rename (sed s command) indicates to replace the regex ^ with Unix_. The caret (^) is a special character that means start of the line.
We had a problem printing with v49something.
I blocked tools.google.com on localhost temporarily so that I could install previous version and prevent updating to the version that is breaking the label printing.
So, in /etc/hosts I added:
0.0.0.0 tools.google.com
Not a perfect solution, but was perfect for us.
There are two common approaches for this:
Specify http-proxy-
options in your /etc/.subversion/servers or %APPDATA%\Subversion\servers file,
Use --config-option
command-line option to specify the same http-proxy-
options in single command-line you run. For example,
svn checkout ^
--config-option servers:global:http-proxy-host=<PROXY-HOST> ^
--config-option servers:global:http-proxy-port=<PORT> <REPO-URL> <LWC-DIR>
If you are on Windows, you can also write http-proxy-
options to Windows Registry. It's pretty handy if you need to apply proxy settings in Active Directory environment via Group Policy Objects.
I have re-factored the code in my original answer. I have removed the recursion and removed the assumed existence overhead.
function roughSizeOfObject( object ) {
var objectList = [];
var stack = [ object ];
var bytes = 0;
while ( stack.length ) {
var value = stack.pop();
if ( typeof value === 'boolean' ) {
bytes += 4;
}
else if ( typeof value === 'string' ) {
bytes += value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes += 8;
}
else if
(
typeof value === 'object'
&& objectList.indexOf( value ) === -1
)
{
objectList.push( value );
for( var i in value ) {
stack.push( value[ i ] );
}
}
}
return bytes;
}
editText.setSelection
is the magic here. Basically selection gives you place cursor at any position you want.
EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());
This places cursor to end of EditText. Basically editText.getText().length()
gives you text length. Then you use setSelection
with length.
editText.setSelection(0);
It is for setting cursor at start position (0).
Instead of "right click"....start your session (once you're in the command prompt window) by keying Alt/SpaceBar. That will open the Command Prompt window menu and you'll see your familiar, underlined keyboard command shortcuts, just like in Windows GUI.
Good luck!
Maybe you have no Comments record with such primary key, then you should use this code:
try:
comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
comment = None
final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(currentTime));
I'm coming to python from R, and R's head()
function wraps lines in a really convenient way for looking at data:
> head(cbind(mtcars, mtcars, mtcars))
mpg cyl disp hp drat wt qsec vs am gear carb mpg cyl
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 21.0 6
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 21.0 6
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 22.8 4
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 21.4 6
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 18.7 8
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 18.1 6
disp hp drat wt qsec vs am gear carb mpg cyl disp hp
Mazda RX4 160 110 3.90 2.620 16.46 0 1 4 4 21.0 6 160 110
Mazda RX4 Wag 160 110 3.90 2.875 17.02 0 1 4 4 21.0 6 160 110
Datsun 710 108 93 3.85 2.320 18.61 1 1 4 1 22.8 4 108 93
Hornet 4 Drive 258 110 3.08 3.215 19.44 1 0 3 1 21.4 6 258 110
Hornet Sportabout 360 175 3.15 3.440 17.02 0 0 3 2 18.7 8 360 175
Valiant 225 105 2.76 3.460 20.22 1 0 3 1 18.1 6 225 105
drat wt qsec vs am gear carb
Mazda RX4 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 3.90 2.875 17.02 0 1 4 4
Datsun 710 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 3.15 3.440 17.02 0 0 3 2
Valiant 2.76 3.460 20.22 1 0 3 1
I developed the following little python function to mimic this functionality:
def rhead(x, nrow = 6, ncol = 4):
pd.set_option('display.expand_frame_repr', False)
seq = np.arange(0, len(x.columns), ncol)
for i in seq:
print(x.loc[range(0, nrow), x.columns[range(i, min(i+ncol, len(x.columns)))]])
pd.set_option('display.expand_frame_repr', True)
(it depends on pandas and numpy, obviously)
If you have Android installed in windows, you will also find it here: C:\Program Files\Android\jdk\microsoft_dist_openjdk_1.8.0.25\jre\bin
Surround it with an \mbox{}
Check for a local or environment variables for a variable called LOL in Bash:
el@server /home/el $ set | grep LOL
el@server /home/el $
el@server /home/el $ env | grep LOL
el@server /home/el $
Sanity check, no local or environment variable called LOL.
Set a local variable called LOL in local, but not environment. So set it:
el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ env | grep LOL
el@server /home/el $
Variable 'LOL' exists in local variables, but not environment variables. LOL will disappear if you restart the terminal, logout/login or run exec bash
.
Set a local variable, and then clear out all local variables in Bash
el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ exec bash
el@server /home/el $ set | grep LOL
el@server /home/el $
You could also just unset the one variable:
el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ unset LOL
el@server /home/el $ set | grep LOL
el@server /home/el $
Local variable LOL is gone.
Promote a local variable to an environment variable:
el@server /home/el $ DOGE="such variable"
el@server /home/el $ export DOGE
el@server /home/el $ set | grep DOGE
DOGE='such variable'
el@server /home/el $ env | grep DOGE
DOGE=such variable
Note that exporting makes it show up as both a local variable and an environment variable.
Exported variable DOGE above survives a Bash reset:
el@server /home/el $ exec bash
el@server /home/el $ env | grep DOGE
DOGE=such variable
el@server /home/el $ set | grep DOGE
DOGE='such variable'
Unset all environment variables:
You have to pull out a can of Chuck Norris to reset all environment variables without a logout/login:
el@server /home/el $ export CAN="chuck norris"
el@server /home/el $ env | grep CAN
CAN=chuck norris
el@server /home/el $ set | grep CAN
CAN='chuck norris'
el@server /home/el $ env -i bash
el@server /home/el $ set | grep CAN
el@server /home/el $ env | grep CAN
You created an environment variable, and then reset the terminal to get rid of them.
Or you could set and unset an environment variable manually like this:
el@server /home/el $ export FOO="bar"
el@server /home/el $ env | grep FOO
FOO=bar
el@server /home/el $ unset FOO
el@server /home/el $ env | grep FOO
el@server /home/el $
For reference, be aware that you might be dismissing the wrong view controller. For example, if you have an alert box or modal showing on top of another modal. (You could have a Twitter post alert showing on top of your current modal alert, for example). In this case, you need to call dismiss twice, or use an unwind segue.
I also like to build locators from up to bottom like:
//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']
It's pretty simple, as we just search btn-group
with button[contains(.,'Arcade Reader')]
and get it's button[@name='settings']
That's just another option to build xPath locators
What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:
getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");
or even simplify more
getGroupButton("Arcade Reader", "delete").click();
As of version 4.5 Microsoft changed the way it stores the .NET Framework indicator in the registry. There official guidance on how to retrieve the .NET framework and the CLR versions can be found here: https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx
I am including modified version of their code to address the bounty question of how you determine the .NET framework for 4.5 and higher here:
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace stackoverflowtesting
{
class Program
{
static void Main(string[] args)
{
Dictionary<int, String> mappings = new Dictionary<int, string>();
mappings[378389] = "4.5";
mappings[378675] = "4.5.1 on Windows 8.1";
mappings[378758] = "4.5.1 on Windows 8, Windows 7 SP1, and Vista";
mappings[379893] = "4.5.2";
mappings[393295] = "4.6 on Windows 10";
mappings[393297] = "4.6 on Windows not 10";
using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
{
int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
if (true)
{
Console.WriteLine("Version: " + mappings[releaseKey]);
}
}
int a = Console.Read();
}
}
}
PerformSelector:WithObject always takes an object, so in order to pass arguments like int/double/float etc..... You can use something like this.
//NSNumber is an object..
[self performSelector:@selector(setUserAlphaNumber:) withObject: [NSNumber numberWithFloat: 1.0f]
afterDelay:1.5];
-(void) setUserAlphaNumber: (NSNumber*) number{
[txtUsername setAlpha: [number floatValue] ];
}
Same way you can use [NSNumber numberWithInt:] etc.... and in the receiving method you can convert the number into your format as [number int] or [number double].
Don't confuse, if you won't give any strWindowFeatures then it will open in a new tab.
window.open('https://play.google.com/store/apps/details?id=com.drishya');
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = context instanceof Activity ? (Activity) context : null;
}
This is kind of hacky, but it works.
I used JavascriptExecutor
and added a div
to the HTML, and changed the text in the div
to $('#prettyTime').val()
I then used Selenium to retrieve the div
and grab its value. After testing the correctness of the value, I removed the div that was just created.
For those who still don't get the accepted solution :
Add
import React from 'react'
import ReactDOM from 'react-dom'
at the top of the file.
Think of it like this: the List
interface has methods like add(int index, E element)
, set(int index, E element)
. The contract is that once you added an element at position X you will find it there unless you add or remove elements before it.
If any list implementation would store elements in some order other than based on the index, the above list methods would make no sense.
You can remove the white space padding by setting bbox_inches="tight"
in savefig
:
plt.savefig("test.png",bbox_inches='tight')
You'll have to put the argument to bbox_inches
as a string, perhaps this is why it didn't work earlier for you.
Possible duplicates:
Matplotlib plots: removing axis, legends and white spaces
Corrected;
/*
return true if the array is not empty
return false if it is empty
*/
function is_array_empty($arr){
if(is_array($arr)){
foreach($arr as $key => $value){
if(!empty($value) || $value != NULL || $value != ""){
return true;
break;//stop the process we have seen that at least 1 of the array has value so its not empty
}
}
return false;
}
}
This is to complement Marc B's answer with an example, while it may look quite long, it's a safe way to remove a parameter. In this example we remove page_number
<?php
$x = 'http://url.com/search/?location=london&page_number=1';
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['page_number']);
$string = http_build_query($params);
var_dump($string);
I Use this query:
select floor(RAND() * (SELECT MAX(key) FROM table)) from table limit 10
query time:0.016s
Another alternative:
myPlanetsList.Select(i => i.Moons).Sum();
I think a much easier way is to use ASIHTTPRequest. Three lines of code can accomplish this:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];
UPDATE: I should mention that ASIHTTPRequest is no longer maintained. The author has specifically advised people to use other framework instead, like AFNetworking
As far as I can tell what you could do is "retire" your previous app and redirect all users to your new app. This procedure is not supported by Google (tsk... tsk...), but it could be implemented in four steps:
Change the current application to show a message to the users about the upgrade and redirect them to the new app listing. Probably a full screen message would do with some friendly text. This message could be triggered remotely ideally, but a cut-off date can be used too. (But then that will be a hard deadline for you, so be careful... ;))
Release the modified old app as an upgrade, maybe with some feature upgrades/bug fixes too, to "sweeten the deal" to the users. Still there is no guarantee that all users will upgrade, but probably the majority will do.
Prepare your new app with the updated package name and upload it to the store, then trigger the message in the old app (or just wait until it expires, if that was your choice).
Unpublish the old app in Play Store to avoid any new installs. Unpublishing an app doesn't mean the users who already installed it won't have access to it anymore, but at least the potential new users won't find it on the market.
Not ideal and can be annoying to the users, sometimes even impossible to implement due to the status/possibilities of the app. But since Google left us no choice this is the only way to migrate the users of the old apps to a "new" one (even if it is not really new). Not to mention that if you don't have access to the sources and code signing details for the old app then all you could do is hoping that he users will notice the new app...
If anybody figured out a better way by all means: please do tell.
The interesting thing about UITableViewStyleGrouped is that the tableView adds the style to the cells and not to the TableView.
The style is added as backgroundView to the cells as a class called UIGroupTableViewCellBackground which handles drawing different background according to the position of the cell in the section.
So a very simple solution will be to use UITableViewStyleGrouped, set the backgroundColor of the table to clearColor, and simply replace the backgroundView of the cell in cellForRow:
cell.backgroundView = [[[UIView alloc] initWithFrame:cell.bounds] autorelease];
to return 1-6 like a dice basically,
return Math.round(Math.random() * 5 + 1);
I faced the same issue, It got fixed after keeping issuer subject value in the certificate as it is as subject of issuer certificate.
so please check "issuer subject value in the certificate(cert.pem) == subject of issuer (CA.pem)"
openssl verify -CAfile CA.pem cert.pem
cert.pem: OK
The differences are covered at the PostgreSQL documentation for date/time types. Yes, the treatment of TIME
or TIMESTAMP
differs between one WITH TIME ZONE
or WITHOUT TIME ZONE
. It doesn't affect how the values are stored; it affects how they are interpreted.
The effects of time zones on these data types is covered specifically in the docs. The difference arises from what the system can reasonably know about the value:
With a time zone as part of the value, the value can be rendered as a local time in the client.
Without a time zone as part of the value, the obvious default time zone is UTC, so it is rendered for that time zone.
The behaviour differs depending on at least three factors:
WITH TIME ZONE
or WITHOUT TIME ZONE
) of the value.Here are examples covering the combinations of those factors:
foo=> SET TIMEZONE TO 'Japan';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 00:00:00+09
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 06:00:00+09
(1 row)
foo=> SET TIMEZONE TO 'Australia/Melbourne';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 00:00:00+11
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 08:00:00+11
(1 row)
How about
List<object> collection = new List<object>((IEnumerable)myObject);
When you create reversed_arr
you are creating a view into the original array. You can then change the original array, and the view will update to reflect the changes.
Are you re-creating the view more often than you need to? You should be able to do something like this:
arr = np.array(some_sequence)
reversed_arr = arr[::-1]
do_something(arr)
look_at(reversed_arr)
do_something_else(arr)
look_at(reversed_arr)
I'm not a numpy expert, but this seems like it would be the fastest way to do things in numpy. If this is what you are already doing, I don't think you can improve on it.
P.S. Great discussion of numpy views here:
Use the LayoutInflater as I shown below.
public View myView() {
View v; // Creating an instance for View Object
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.myview, null);
TextView text1 = v.findViewById(R.id.dolphinTitle);
Button btn1 = v.findViewById(R.id.dolphinMinusButton);
TextView text2 = v.findViewById(R.id.dolphinValue);
Button btn2 = v.findViewById(R.id.dolphinPlusButton);
return v;
}
I had this issue under CygWin in Windows. I have read elsewhere that Java does not understand the CygWin paths (/cygdrive/c/some/dir
instead of C:\some\dir
) - so I used a relative path instead: ../../some/dir/sbt-launch.jar
.
Set Body as raw and form the array as follows:
There isn't a system feature to change the height of the table based upon the contents of the tableview. Having said that, it is possible to programmatically change the height of the tableview based upon the contents, specifically based upon the contentSize
of the tableview (which is easier than manually calculating the height yourself). A few of the particulars vary depending upon whether you're using the new autolayout that's part of iOS 6, or not.
But assuming you're configuring your table view's underlying model in viewDidLoad
, if you want to then adjust the height of the tableview, you can do this in viewDidAppear
:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self adjustHeightOfTableview];
}
Likewise, if you ever perform a reloadData
(or otherwise add or remove rows) for a tableview, you'd want to make sure that you also manually call adjustHeightOfTableView
there, too, e.g.:
- (IBAction)onPressButton:(id)sender
{
[self buildModel];
[self.tableView reloadData];
[self adjustHeightOfTableview];
}
So the question is what should our adjustHeightOfTableview
do. Unfortunately, this is a function of whether you use the iOS 6 autolayout or not. You can determine if you have autolayout turned on by opening your storyboard or NIB and go to the "File Inspector" (e.g. press option+command+1 or click on that first tab on the panel on the right):
Let's assume for a second that autolayout was off. In that case, it's quite simple and adjustHeightOfTableview
would just adjust the frame
of the tableview:
- (void)adjustHeightOfTableview
{
CGFloat height = self.tableView.contentSize.height;
CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;
// if the height of the content is greater than the maxHeight of
// total space on the screen, limit the height to the size of the
// superview.
if (height > maxHeight)
height = maxHeight;
// now set the frame accordingly
[UIView animateWithDuration:0.25 animations:^{
CGRect frame = self.tableView.frame;
frame.size.height = height;
self.tableView.frame = frame;
// if you have other controls that should be resized/moved to accommodate
// the resized tableview, do that here, too
}];
}
If your autolayout was on, though, adjustHeightOfTableview
would adjust a height constraint for your tableview:
- (void)adjustHeightOfTableview
{
CGFloat height = self.tableView.contentSize.height;
CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;
// if the height of the content is greater than the maxHeight of
// total space on the screen, limit the height to the size of the
// superview.
if (height > maxHeight)
height = maxHeight;
// now set the height constraint accordingly
[UIView animateWithDuration:0.25 animations:^{
self.tableViewHeightConstraint.constant = height;
[self.view setNeedsUpdateConstraints];
}];
}
For this latter constraint-based solution to work with autolayout, we must take care of a few things first:
Make sure your tableview has a height constraint by clicking on the center button in the group of buttons here and then choose to add the height constraint:
Then add an IBOutlet
for that constraint:
Make sure you adjust other constraints so they don't conflict if you adjust the size tableview programmatically. In my example, the tableview had a trailing space constraint that locked it to the bottom of the screen, so I had to adjust that constraint so that rather than being locked at a particular size, it could be greater or equal to a value, and with a lower priority, so that the height and top of the tableview would rule the day:
What you do here with other constraints will depend entirely upon what other controls you have on your screen below the tableview. As always, dealing with constraints is a little awkward, but it definitely works, though the specifics in your situation depend entirely upon what else you have on the scene. But hopefully you get the idea. Bottom line, with autolayout, make sure to adjust your other constraints (if any) to be flexible to account for the changing tableview height.
As you can see, it's much easier to programmatically adjust the height of a tableview if you're not using autolayout, but in case you are, I present both alternatives.
window.location.replace('http://sidanmor.com');
It's better than using window.location.href = 'http://sidanmor.com';
Using replace()
is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
window.location.href
If you want to simulate an HTTP redirect, use
window.location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");
// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";
Taken from here: How to redirect to another page in jQuery?
Since question was regarding clunkiness of property checking, and one regular usecase for that being validation of function argument options objects, thought I'd mention a library-free short way of testing existence of multiple properties. Disclaimer: It does require ECMAScript 5 (but IMO anyone still using IE8 deserves a broken web).
function f(opts) {
if(!["req1","req2"].every(opts.hasOwnProperty, opts)) {
throw new Error("IllegalArgumentException");
}
alert("ok");
}
f({req1: 123}); // error
f({req1: 123, req2: 456}); // ok
By default, it does not. However, you can use the MVCHtml5Toolkit NuGet package that has HTML helpers that can output HTML5. For your example, after installing the toolkit you can then use the following HTML helper call:
@Html.Html5TextBoxFor(m => m.Email, InputTypes.InputType.Email)
This will output the following HTML:
<input id="Email" name="Email" placeholder="E-Mail" type="Email" value="">
As can be seen, the placeholder is now correctly rendered.
I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:
var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
.Select(r => new ResultGrouping {
IdObj1= r.Key.IdObj1,
IdObj2= r.Key.IdObj2,
IdObj3= r.Key.IdObj3,
Results = r.ToArray(),
Count = r.Count()
});
private class ResultGrouping
{
public short IdObj1{ get; set; }
public short IdObj2{ get; set; }
public int IdObj3{ get; set; }
public ResultCsvImport[] Results { get; set; }
public int Count { get; set; }
}
Where resultRecords
is my initial list I'm grouping, and its a List<ResultCsvImport>
. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3
from selenium.webdriver.support.ui import WebDriverWait
chrome_options = webdriver.ChromeOptions()
chrome_options.headless = True
self.driver = webdriver.Chrome(
executable_path=DRIVER_PATH, chrome_options=chrome_options)
if 'name' in mydict:
is the preferred, pythonic version. Use of has_key()
is discouraged, and this method has been removed in Python 3.
Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block
or display: inline-block
to transform them:
#whatever:after {
content: "\24B6";
display: inline-block;
transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
As of MySQL 5.6 its easy-peasy... give it a try:
create table tweet (
id integer not null auto_increment primary key,
stamp_created timestamp default now(),
stamp_updated timestamp default now() on update now(),
message varchar(163)
)
In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/) to create instances each and every time there was a operation to be done.So my code was to be designed like:
public abstract class EO {
@Autowired
protected SmsNotificationService smsNotificationService;
@Autowired
protected SendEmailService sendEmailService;
...
protected abstract void executeOperation(GenericMessage gMessage);
}
public final class OperationsExecutor {
public enum OperationsType {
ENROLL, CAMPAIGN
}
private OperationsExecutor() {
}
public static Object delegateOperation(OperationsType type, Object obj)
{
switch(type) {
case ENROLL:
if (obj == null) {
return new EnrollOperation();
}
return EnrollOperation.validateRequestParams(obj);
case CAMPAIGN:
if (obj == null) {
return new CampaignOperation();
}
return CampaignOperation.validateRequestParams(obj);
default:
throw new IllegalArgumentException("OperationsType not supported.");
}
}
}
@Configurable(dependencyCheck = true)
public class CampaignOperation extends EO {
@Override
public void executeOperation(GenericMessage genericMessage) {
LOGGER.info("This is CAMPAIGN Operation: " + genericMessage);
}
}
Initially to inject the dependencies in the abstract class I tried all stereotype annotations like @Component, @Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **@Configurable(dependencyCheck = true)**
annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.
<context:annotation-config />
<context:component-scan base-package="com.xyz" />
I also tried these other references to find a solution:
Please try using **@Configurable(dependencyCheck = true)**
and update this post, I might try helping you if you face any problems.
To install Python package from github, you need to clone that repository.
git clone https://github.com/jkbr/httpie.git
Then just run the setup.py file from that directory,
sudo python setup.py install
Nowadays, in iOS 13+ and macOS 10.15+, we might use ListFormatter
:
let formatter = ListFormatter()
let names = ["Moe", "Larry", "Curly"]
if let string = formatter.string(from: names) {
print(string)
}
That will produce a nice, natural language string representation of the list. A US user will see:
Moe, Larry, and Curly
It will support any languages for which (a) your app has been localized; and (b) the user’s device is configured. For example, a German user with an app supporting German localization, would see:
Moe, Larry und Curly
jQuery has an excellent function for looping through a set of elements: .each()
$('#formId').children().each(
function(){
//access to form element via $(this)
}
);
grab the input values after form submission in php
$start_time = $_POST('start_time');
$end_time =$_POST('end_time');
$start = $start_time;
$end = $end_time;
$datetime1 = new DateTime($end);
$datetime2 = new DateTime($start);
//echo $datetime1->format('H:i:s');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%h:%i');
$time = explode(":",$elapsed);
$hours = $time[0];
$minutes = $time[1];
$tminutes = $minutes + ($hours*60);
the variable $tminutes is total diff in minutes , working hour is $hour . this code is for php use this logic and convert this code to js
I've found this query also very helpful in SqlServerCentral, here is the link to original post
select name=object_schema_name(object_id) + '.' + object_name(object_id)
, rows=sum(case when index_id < 2 then row_count else 0 end)
, reserved_kb=8*sum(reserved_page_count)
, data_kb=8*sum( case
when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count
else lob_used_page_count + row_overflow_used_page_count
end )
, index_kb=8*(sum(used_page_count)
- sum( case
when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count
else lob_used_page_count + row_overflow_used_page_count
end )
)
, unused_kb=8*sum(reserved_page_count-used_page_count)
from sys.dm_db_partition_stats
where object_id > 1024
group by object_id
order by
rows desc
In my database they gave different results between this query and the 1st answer.
Hope somebody finds useful
What you need to do is to call pthread_mutex_lock to secure a mutex, like this:
pthread_mutex_lock(&mutex);
Once you do this, any other calls to pthread_mutex_lock(mutex)
will not return until you call pthread_mutex_unlock
in this thread. So if you try to call pthread_create, you will be able to create a new thread, and that thread will be able to (incorrectly) use the shared resource. You should call pthread_mutex_lock
from within your fooAPI
function, and that will cause the function to wait until the shared resource is available.
So you would have something like this:
#include <pthread.h>
#include <stdio.h>
int sharedResource = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* fooAPI(void* param)
{
pthread_mutex_lock(&mutex);
printf("Changing the shared resource now.\n");
sharedResource = 42;
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
pthread_t thread;
// Really not locking for any reason other than to make the point.
pthread_mutex_lock(&mutex);
pthread_create(&thread, NULL, fooAPI, NULL);
sleep(1);
pthread_mutex_unlock(&mutex);
// Now we need to lock to use the shared resource.
pthread_mutex_lock(&mutex);
printf("%d\n", sharedResource);
pthread_mutex_unlock(&mutex);
}
Edit: Using resources across processes follows this same basic approach, but you need to map the memory into your other process. Here's an example using shmem:
#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/wait.h>
struct shared {
pthread_mutex_t mutex;
int sharedResource;
};
int main()
{
int fd = shm_open("/foo", O_CREAT | O_TRUNC | O_RDWR, 0600);
ftruncate(fd, sizeof(struct shared));
struct shared *p = (struct shared*)mmap(0, sizeof(struct shared),
PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
p->sharedResource = 0;
// Make sure it can be shared across processes
pthread_mutexattr_t shared;
pthread_mutexattr_init(&shared);
pthread_mutexattr_setpshared(&shared, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&(p->mutex), &shared);
int i;
for (i = 0; i < 100; i++) {
pthread_mutex_lock(&(p->mutex));
printf("%d\n", p->sharedResource);
pthread_mutex_unlock(&(p->mutex));
sleep(1);
}
munmap(p, sizeof(struct shared*));
shm_unlink("/foo");
}
Writing the program to make changes to p->sharedResource is left as an exercise for the reader. :-)
Forgot to note, by the way, that the mutex has to have the PTHREAD_PROCESS_SHARED attribute set, so that pthreads will work across processes.
I have just figured out something with this error.
Just make sure that the library jar file contains the compiled R class under android.support.v7.appcompat package and copy all the res in the v7 appcompat support "project" in your ANDROID_SDK_HOME/extras/android/support/v7/appcompat folder.
I use Netbeans with the Android plugin and this solved my issue.
You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick
.
You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:
var rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
return {_x000D_
country: elem.country,_x000D_
launches: elem.launches+10,_x000D_
} _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
Save the execution file on your desktop Make sure you note the name of your file Go to start and type cmd right click on it
select run as administrator press enter
then you something below
C:\Users\your computer name\Desktop>
If you are seeing
C:\Windows\system32>
make sure you change it using CD
type the name of your file
C:\Users\your computer name\Desktop>the name of the file your copy.exe/ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck
The best way to achieve would be to use Apache Commons Exec as I use it for production without problems even for Java 8 environment because of the fact that it lets you execute any external process (including python, bash etc) in synchronous
and asynchronous
way by using watchdogs.
CommandLine cmdLine = new CommandLine("python");
cmdLine.addArgument("/my/python/script/script.py");
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000);
Executor executor = new DefaultExecutor();
executor.setExitValue(1);
executor.setWatchdog(watchdog);
executor.execute(cmdLine, resultHandler);
// some time later the result handler callback was invoked so we
// can safely request the exit value
resultHandler.waitFor();
Complete source code for a small but complete POC is shared here that addresses another concern in this post;
Since Snow Leopard, up to Catalina and Big Sur, every version of macOS supports this:
sudo lsof -iTCP -sTCP:LISTEN -n -P
Personally I've end up with this simple function in my ~/.bash_profile
:
listening() {
if [ $# -eq 0 ]; then
sudo lsof -iTCP -sTCP:LISTEN -n -P
elif [ $# -eq 1 ]; then
sudo lsof -iTCP -sTCP:LISTEN -n -P | grep -i --color $1
else
echo "Usage: listening [pattern]"
fi
}
Then listening
command gives you a listing of processes listening on some port and listening smth
greps this for some pattern.
Having this, it's quite easy to ask about particular process, e.g. listening dropbox
, or port, e.g. listening 22
.
lsof
command has some specialized options for asking about port, protocol, process etc. but personally I've found above function much more handy, since I don't need to remember all these low-level options. lsof
is quite powerful tool, but unfortunately not so comfy to use.
$(document).ready(function () {
$('#EmployeeId').val("fgg");
//Or
$('.textBoxEmployeeNumber > input').val("fgg");
//Or
$('.textBoxEmployeeNumber').find('input').val("fgg");
});
I fixed this issue starting with @hallodom's answer. All my inputs were contained within li's, so all I had to do was set the li overflow:hidden for it to remove that excess input overflow.
.ie7 form li {
width:100%;
overflow:hidden;
}
.ie7 input {
width:100%;
}
Aliases can be used only if they were introduced in the preceding step. So aliases in the SELECT
clause can be used in the ORDER BY
but not the GROUP BY
clause.
Reference: Microsoft T-SQL Documentation for further reading.
FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP
Hope this helps.
You can view this dump from the UNIX console.
The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.
E.g.:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"
You can view the dump from the console on the mentioned path.
This works.
<html>
<head>
<script type = "text/javascript">
function write_below(form)
{
var input = document.forms.write.input_to_write.value;
document.getElementById('write_here').innerHTML="Your input was:"+input;
return false;
}
</script>
</head>
<!--Insert more code here-->
<body>
<form name='write' onsubmit='return write_below(this);'>
<input type = "text" name='input_to_write'>
<input type = "button" value = "submit" />
</form>
<div id='write_here'></div></body>
</html>
Returning false from the function never posts it to other page,but does edit the html content.
For tools like jarsigner
which is implemented in Java.
JAVA_TOOL_OPTIONS=-Duser.language=en jarsigner
In the component.css or app.css add Icon Color styles
.material-icons.color_green { color: #00FF00; }
.material-icons.color_white { color: #FFFFFF; }
In the component.html set the icon class
<mat-icon class="material-icons color_green">games</mat-icon>
<mat-icon class="material-icons color_white">cloud</mat-icon>
ng build
I use the following and it does exactly what you are looking for:
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
UpdateCheckInfo info = null;
info = ad.CheckForDetailedUpdate();
if (info.IsUpdateRequired)
{
ad.UpdateAsync(); // I like the update dialog
MessageBox.Show("Application was upgraded and will now restart.");
Environment.Exit(0);
}
Try This:
/// <summary>
/// AlphabetizeDropDownList alphabetizes a given dropdown list by it's displayed text.
/// </summary>
/// <param name="dropDownList">The drop down list you wish to modify.</param>
/// <remarks></remarks>
private void AlphabetizeDropDownList(ref DropDownList dropDownList)
{
//Create a datatable to sort the drop down list items
DataTable machineDescriptionsTable = new DataTable();
machineDescriptionsTable.Columns.Add("DescriptionCode", typeof(string));
machineDescriptionsTable.Columns.Add("UnitIDString", typeof(string));
machineDescriptionsTable.AcceptChanges();
//Put each of the list items into the datatable
foreach (ListItem currentDropDownListItem in dropDownList.Items) {
string currentDropDownUnitIDString = currentDropDownListItem.Value;
string currentDropDownDescriptionCode = currentDropDownListItem.Text;
DataRow currentDropDownDataRow = machineDescriptionsTable.NewRow();
currentDropDownDataRow["DescriptionCode"] = currentDropDownDescriptionCode.Trim();
currentDropDownDataRow["UnitIDString"] = currentDropDownUnitIDString.Trim();
machineDescriptionsTable.Rows.Add(currentDropDownDataRow);
machineDescriptionsTable.AcceptChanges();
}
//Sort the data table by description
DataView sortedView = new DataView(machineDescriptionsTable);
sortedView.Sort = "DescriptionCode";
machineDescriptionsTable = sortedView.ToTable();
//Clear the items in the original dropdown list
dropDownList.Items.Clear();
//Create a dummy list item at the top
ListItem dummyListItem = new ListItem(" ", "-1");
dropDownList.Items.Add(dummyListItem);
//Begin transferring over the items alphabetically from the copy to the intended drop
downlist
foreach (DataRow currentDataRow in machineDescriptionsTable.Rows) {
string currentDropDownValue = currentDataRow["UnitIDString"].ToString().Trim();
string currentDropDownText = currentDataRow["DescriptionCode"].ToString().Trim();
ListItem currentDropDownListItem = new ListItem(currentDropDownText, currentDropDownValue);
//Don't deal with dummy values in the list we are transferring over
if (!string.IsNullOrEmpty(currentDropDownText.Trim())) {
dropDownList.Items.Add(currentDropDownListItem);
}
}
}
This will take a given drop down list with a Text and a Value property of the list item and put them back into the given drop down list. Best of Luck!
Extracted from @Resord's comments above. This one worked for me and more closely inclined with the question.
$(this).parent().closest('.a');
Thanks
Though this is an old post and have many answers, but here I have my version of code to upload the file to sharepoint 2013 using CSOM(c#)
I hope if you are working with downloading and uploading files then you know how to create Clientcontext
object and Web
object
/* Assuming you have created ClientContext object and Web object*/
string listTitle = "List title where you want your file to upload";
string filePath = "your file physical path";
List oList = web.Lists.GetByTitle(listTitle);
clientContext.Load(oList.RootFolder);//to load the folder where you will upload the file
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.Overwrite = true;
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileInfo.Url = fileName;
File fileToUpload = fileCollection.Add(fileInfo);
clientContext.ExecuteQuery();
fileToUpload.CheckIn("your checkin comment", CheckinType.MajorCheckIn);
if (oList.EnableMinorVersions)
{
fileToUpload.Publish("your publish comment");
clientContext.ExecuteQuery();
}
if (oList.EnableModeration)
{
fileToUpload.Approve("your approve comment");
}
clientContext.ExecuteQuery();
And here is the code for download
List oList = web.Lists.GetByTitle("ListNameWhereFileExist");
clientContext.Load(oList);
clientContext.Load(oList.RootFolder);
clientContext.Load(oList.RootFolder.Files);
clientContext.ExecuteQuery();
FileCollection fileCollection = oList.RootFolder.Files;
File SP_file = fileCollection.GetByUrl("fileNameToDownloadWithExtension");
clientContext.Load(SP_file);
clientContext.ExecuteQuery();
var Local_stream = System.IO.File.Open("c:/testing/" + SP_file.Name, System.IO.FileMode.CreateNew);
var fileInformation = File.OpenBinaryDirect(clientContext, SP_file.ServerRelativeUrl);
var Sp_Stream = fileInformation.Stream;
Sp_Stream.CopyTo(Local_stream);
Still there are different ways I believe that can be used to upload and download.
right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.
This is the best answer to solve the problem
I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.
java.lang.IllegalArgumentException: No enum constant
Also the problem was when we at Parcelize read moment write some short if.
My solution for this was
1.Create companion object with parsing method.
enum class CarsType {
@Json(name = "SMALL")
SMALL,
@Json(name = "BIG")
BIG;
companion object {
fun nullableValueOf(name: String?) = when (name) {
null -> null
else -> valueOf(name)
}
}
}
2. In Parcerable read place use it like this
data class CarData(
val carId: String? = null,
val carType: CarsType?,
val data: String?
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
CarsType.nullableValueOf(parcel.readString()),
parcel.readString())
Based on @shomrat's answer, here is a snippet that automatically writes datetime like this (a bit similar to StackOverflow's date for answers: answered Nov 6 '16 at 11:51
):
today, 11:23
or
yersterday, 11:23
or (if different but same year than today)
6 Nov, 11:23
or (if another year than today)
6 Nov 2016, 11:23
function timeConverter(t) {
var a = new Date(t * 1000);
var today = new Date();
var yesterday = new Date(Date.now() - 86400000);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
if (a.setHours(0,0,0,0) == today.setHours(0,0,0,0))
return 'today, ' + hour + ':' + min;
else if (a.setHours(0,0,0,0) == yesterday.setHours(0,0,0,0))
return 'yesterday, ' + hour + ':' + min;
else if (year == today.getFullYear())
return date + ' ' + month + ', ' + hour + ':' + min;
else
return date + ' ' + month + ' ' + year + ', ' + hour + ':' + min;
}
To use Thickness
you need to create/change your project .NET framework
platform version to 4.5. becaus this method available only in version 4.5. (Also you can just download PresentationFramework.dll and give referense to this dll, without create/change your .NET framework
version to 4.5.)
But if you want to do this simple, You can use this code:
MyControl.Margin = new Padding(int left, int top, int right, int bottom);
also
MyControl.Margin = new Padding(int all);
This is simple and no needs any changes to your project
You forgot to add std::
namespace prefix to vector
class name.
You can't change PHP version by .htaccess.
you need to get your server updated, for PHP 5.3 or you can find another host, which serves PHP 5.3 on shared hosting.
You can use 'unique'(aliases: uniq) filter in angular.filter module
usage: colection | uniq: 'property'
you can also filter by nested properties: colection | uniq: 'property.nested_property'
What you can do, is something like that..
function MainController ($scope) {
$scope.orders = [
{ id:1, customer: { name: 'foo', id: 10 } },
{ id:2, customer: { name: 'bar', id: 20 } },
{ id:3, customer: { name: 'foo', id: 10 } },
{ id:4, customer: { name: 'bar', id: 20 } },
{ id:5, customer: { name: 'baz', id: 30 } },
];
}
HTML: We filter by customer id, i.e remove duplicate customers
<th>Customer list: </th>
<tr ng-repeat="order in orders | unique: 'customer.id'" >
<td> {{ order.customer.name }} , {{ order.customer.id }} </td>
</tr>
result
Customer list:
foo 10
bar 20
baz 30
perhaps this is what you're looking for: https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/colors.xml
Here is a generic example of using a weak reference and static handler class to resolve the problem (as recommended in the Lint documentation):
public class MyClass{
//static inner class doesn't hold an implicit reference to the outer class
private static class MyHandler extends Handler {
//Using a weak reference means you won't prevent garbage collection
private final WeakReference<MyClass> myClassWeakReference;
public MyHandler(MyClass myClassInstance) {
myClassWeakReference = new WeakReference<MyClass>(myClassInstance);
}
@Override
public void handleMessage(Message msg) {
MyClass myClass = myClassWeakReference.get();
if (myClass != null) {
...do work here...
}
}
}
/**
* An example getter to provide it to some external class
* or just use 'new MyHandler(this)' if you are using it internally.
* If you only use it internally you might even want it as final member:
* private final MyHandler mHandler = new MyHandler(this);
*/
public Handler getHandler() {
return new MyHandler(this);
}
}
The following function converts an integer to binary in a string (n is the number of bits):
// Convert an integer to binary (in a string)
void int2bin(unsigned integer, char* binary, int n=8)
{
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='\0';
}
Test online on repl.it.
Source : AnsWiki.
The following function converts an integer to binary in a string and allocate memory for the string (n is the number of bits):
// Convert an integer to binary (in a string)
char* int2bin(unsigned integer, int n=8)
{
char* binary = (char*)malloc(n+1);
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='\0';
return binary;
}
This option allows you to write something like printf ("%s", int2bin(78));
but be careful, memory allocated for the string must be free later.
Test online on repl.it.
Source : AnsWiki.
The following function converts an integer to binary in another integer (8 bits maximum):
// Convert an integer to binary (in an unsigned)
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
Test online on repl.it
The following function displays the binary conversion
// Convert an integer to binary and display the result
void int2bin(unsigned integer, int n=8)
{
for (int i=0;i<n;i++)
putchar ( (integer & (int)1<<(n-i-1)) ? '1' : '0' );
}
Test online on repl.it.
Source : AnsWiki.
.child {
width: 100vw;
position: relative;
left: calc(-50vw + 50%);
}
We set the width
of the child element to fill the entire viewport width, then we make it meet the edge of the screen by moving it to the left
by a distance of half the viewport, minus 50% of the parent element's width.
Demo:
* {
box-sizing: border-box;
}
body {
margin: 0;
overflow-x: hidden;
}
.parent {
max-width: 400px;
margin: 0 auto;
padding: 1rem;
position: relative;
background-color: darkgrey;
}
.child {
width: 100vw;
position: relative;
left: calc(-50vw + 50%);
height: 100px;
border: 3px solid red;
background-color: lightgrey;
}
_x000D_
<div class="parent">
Pre
<div class="child">Child</div>
Post
</div>
_x000D_
Browser support for vw and for calc() can generally be seen as IE9 and newer.
Note: This assumes the box model is set to border-box
. Without border-box
, you would also have to subtract paddings and borders, making this solution a mess.
Note: It is encouraged to hide horizontal overflow of your scrolling container, as certain browsers may choose to display a horizontal scrollbar despite there being no overflow.
From here:
The function
ord()
gets the int value of the char. And in case you want to convert back after playing with the number, functionchr()
does the trick.
>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>
In Python 2, there was also the unichr
function, returning the Unicode character whose ordinal is the unichr
argument:
>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'
In Python 3 you can use chr
instead of unichr
.
You remove the original image here:
newImg.animate(css, SPEED, function() {
img.remove();
newImg.removeClass('morpher');
(callback || function() {})();
});
And all that's left behind is newImg
. Then you reset link references the image using #rocket
:
$("#rocket").attr('src', ...
But your newImg
doesn't have an id
attribute let alone an id
of rocket
.
To fix this, you need to remove img
and then set the id
attribute of newImg
to rocket
:
newImg.animate(css, SPEED, function() {
var old_id = img.attr('id');
img.remove();
newImg.attr('id', old_id);
newImg.removeClass('morpher');
(callback || function() {})();
});
And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/
UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:
$("#resetlink").click(function(){
clearInterval(timerRocket);
$("#wrapper").css('top', '250px');
$('.throbber, .morpher').remove(); // Clear out the new stuff.
$("#rocket").show(); // Bring the original back.
});
And in the newImg.load
function, grab the images original size:
var orig = {
width: img.width(),
height: img.height()
};
And finally, the callback for finishing the morphing animation becomes this:
newImg.animate(css, SPEED, function() {
img.css(orig).hide();
(callback || function() {})();
});
New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/
The leaking of $('.throbber, .morpher')
outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.
You can use the java.time
package (since Java8 and late) to get start/end of day/week/month.
The util class example below:
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
public class DateUtil {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public static LocalDateTime startOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
}
public static LocalDateTime endOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
}
public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
}
//note that week starts with Monday
public static LocalDateTime startOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
}
//note that week ends with Sunday
public static LocalDateTime endOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
}
public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
}
public static LocalDateTime startOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDateTime endOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.lastDayOfMonth());
}
public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
}
public static long toMills(final LocalDateTime localDateTime) {
return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
}
public static Date toDate(final LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
}
public static String toString(final LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
}
@Test
public void test() {
//day
final LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
System.out.println("Start of day: " + toString(startOfDay()));
System.out.println("End of day: " + toString(endOfDay()));
System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
final LocalDateTime yesterday = now.minusDays(1);
System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
final LocalDateTime tomorrow = now.plusDays(1);
System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
//week
System.out.println("Start of week: " + toString(startOfWeek()));
System.out.println("End of week: " + toString(endOfWeek()));
System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
final LocalDateTime previousWeek = now.minusWeeks(1);
System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
final LocalDateTime nextWeek = now.plusWeeks(1);
System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
//month
System.out.println("Start of month: " + toString(startOfMonth()));
System.out.println("End of month: " + toString(endOfMonth()));
System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
final LocalDateTime previousMonth = now.minusMonths(1);
System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
final LocalDateTime nextMonth = now.plusMonths(1);
System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
}
}
Test output:
Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false
@mogstad has been kind enough to wrap @stephencelis solution in a Cocoapod:
pod 'libCommonCrypto'
The other pods available did not work for me.
While Dav is correct that the information isn't directly stored, that doesn't mean you can't ever find out. Here are a few things you can do.
git branch -a --contains <commit>
This will tell you all branches which have the given commit in their history. Obviously this is less useful if the commit's already been merged.
If you are working in the repository in which the commit was made, you can search the reflogs for the line for that commit. Reflogs older than 90 days are pruned by git-gc, so if the commit's too old, you won't find it. That said, you can do this:
git reflog show --all | grep a871742
to find commit a871742. Note that you MUST use the abbreviatd 7 first digits of the commit. The output should be something like this:
a871742 refs/heads/completion@{0}: commit (amend): mpc-completion: total rewrite
indicating that the commit was made on the branch "completion". The default output shows abbreviated commit hashes, so be sure not to search for the full hash or you won't find anything.
git reflog show
is actually just an alias for git log -g --abbrev-commit --pretty=oneline
, so if you want to fiddle with the output format to make different things available to grep for, that's your starting point!
If you're not working in the repository where the commit was made, the best you can do in this case is examine the reflogs and find when the commit was first introduced to your repository; with any luck, you fetched the branch it was committed to. This is a bit more complex, because you can't walk both the commit tree and reflogs simultaneously. You'd want to parse the reflog output, examining each hash to see if it contains the desired commit or not.
This is workflow-dependent, but with good workflows, commits are made on development branches which are then merged in. You could do this:
git log --merges <commit>..
to see merge commits that have the given commit as an ancestor. (If the commit was only merged once, the first one should be the merge you're after; otherwise you'll have to examine a few, I suppose.) The merge commit message should contain the branch name that was merged.
If you want to be able to count on doing this, you may want to use the --no-ff
option to git merge
to force merge commit creation even in the fast-forward case. (Don't get too eager, though. That could become obfuscating if overused.) VonC's answer to a related question helpfully elaborates on this topic.
I had the same case . The reason was that I had changed htdocs folder location to another drive and although made appropriate configuration, for physical reasons, when starting apache the drive was not accessible: After making it accessible the problem has been solved . Generally it seems logical that when apache doesn't find all of the components it won't start.
To get a list of threads and their full states using the terminal, you can use the command below:
jstack -l <PID>
Which <PID>
is the id of process running on your computer. To get the process id of your java process you can simply run the jps
command.
Also, you can analyze your thread dump that produced by jstack in TDAs (Thread Dump Analyzer) such fastthread or spotify thread analyzer tool.
In bash, the $LINES
and $COLUMNS
environmental variables should be able to do the trick. The will be set automatically upon any change in the terminal size. (i.e. the SIGWINCH signal)
Broadcasting is really good for this:
row_sums = a.sum(axis=1)
new_matrix = a / row_sums[:, numpy.newaxis]
row_sums[:, numpy.newaxis]
reshapes row_sums from being (3,)
to being (3, 1)
. When you do a / b
, a
and b
are broadcast against each other.
You can learn more about broadcasting here or even better here.
Add the following to your web.config:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxQueryString="32768"/>
</requestFiltering>
</security>
</system.webServer>
See:
http://www.iis.net/ConfigReference/system.webServer/security/requestFiltering/requestLimits
Updated to reflect comments.
requestLimits Element for requestFiltering [IIS Settings Schema]
You may have to add the following in your web.config as well
<system.web>
<httpRuntime maxQueryStringLength="32768" maxUrlLength="65536"/>
</system.web>
See: httpRuntime Element (ASP.NET Settings Schema)
Of course the numbers (32768 and 65536) in the config settings above are just examples. You don't have to use those exact values.
You can do so by these ways.
Add watchpoint
and while debugging you can see variable in debugger window perspective under variable tab.
OR
Add System.out.println("variable = " + variable);
and see in console.
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
Here is an example that's working for me with MVC and Javascript in the Razor. The first function calls an action via ajax on my controller and passes two parameters.
function redirectToAction(var1, var2)
{
try{
var url = '../actionnameinsamecontroller/' + routeId;
$.ajax({
type: "GET",
url: url,
data: { param1: var1, param2: var2 },
dataType: 'html',
success: function(){
},
error: function(xhr, ajaxOptions, thrownError){
alert(error);
}
});
}
catch(err)
{
alert(err.message);
}
}
Use the ajaxStart to start your progress bar code.
$(document).ajaxStart(function(){
try
{
// showing a modal
$("#progressDialog").modal();
var i = 0;
var timeout = 750;
(function progressbar()
{
i++;
if(i < 1000)
{
// some code to make the progress bar move in a loop with a timeout to
// control the speed of the bar
iterateProgressBar();
setTimeout(progressbar, timeout);
}
}
)();
}
catch(err)
{
alert(err.message);
}
});
When the process completes close the progress bar
$(document).ajaxStop(function(){
// hide the progress bar
$("#progressDialog").modal('hide');
});
There are two properties in a TabControl control that manages which tab page is selected.
SelectedIndex which offer the possibility to select it by index (an integer starting from 0 to the number of tabs you have minus one).
SelectedTab which offer the possibility to selected the tab object itself to select.
Setting either of these property will change the currently displayed tab.
Alternatively you can also use the Select method. It comes in three flavour, one where you pass the index of the tab, another the TabPage object itself and the last one a string representing the tab's name.
that is the right behavior.
if you set @item1
to a value the below expression will be true
IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)
Anyway in SQL Server there is not a such function but you can create your own:
CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
RETURN 0
ELSE
RETURN 1
END
Update for 2020: Sticking to the original question of 16x16 versus 32x32 icons: the current recommendation should be to provide a 32x32 icon, skipping 16x16 entirely. All current browsers and devices support 32x32 icons. The icon will routinely be upscaled to as much as 192x192 depending on the environment (assuming there are no larger sizes available or the system didn't recognize them). Upscaling from ultra low resolution has a noticeable effect so better stick to 32x32 as the smallest baseline.
For IE, Microsoft recommends 16x16, 32x32 and 48x48 packed in the favicon.ico file.
For iOS, Apple recommends specific file names and resolutions, at most 180x180 for latest devices running iOS 8.
Android Chrome primarily uses a manifest and also relies on the Apple touch icon.
IE 10 on Windows 8.0 requires PNG pictures and a background color and IE 11 on Windows 8.1 and 10 accepts several PNG pictures declared in a dedicated XML file called browserconfig.xml
.
Safari for Mac OS X El Capitan introduces an SVG icon for pinned tabs.
Some other platforms look for PNG files with various resolutions, like the 96x96 picture for Google TV or the 228x228 picture for Opera Coast.
Look at this favicon pictures list for a complete reference.
TLDR: This favicon generator can generate all these files at once. The generator can also be implemented as a WordPress plugin. Full disclosure: I am the author of this site.
Just add these two lines to $(document).ready in JS as follow:
$(document).ready(function () {
$("div.sidebar nav a").removeClass("active");
$('nav a[href$="'+ window.location.pathname.split("?")[0] +'"]').addClass('active');
});
it is better to use the dollar sign ($) (End with)
$('nav a[href$
instead of (^) (Start with)
$('nav a[href^
because, if you use the (^) sign and you have nested URLs in the navigation menu, (e.g "/account" and "/account/roles")
It will active both of them.
target="_parent"
worked great for me. easy and hassle free!
Like you have mentioned, The default -Xmxsize
(Maximum HeapSize) depends on your system configuration.
Java8 client
takes Larger of 1/64th of your physical memory for your Xmssize
(Minimum HeapSize) and Smaller of 1/4th of your physical memory for your -Xmxsize
(Maximum HeapSize).
Which means if you have a physical memory of 8GB RAM, you will have Xmssize
as Larger of 8*(1/6) and Smaller of -Xmxsize
as 8*(1/4).
You can Check your default HeapSize with
In Windows:
java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"
In Linux:
java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
These default values can also be overrided to your desired amount.
response.setContentType("text/json");
//create the JSON string, I suggest using some framework.
String your_string;
out.write(your_string.getBytes("UTF-8"));
rm -rf ~/anaconda
It was pretty easy. It switched my pointer to Python: https://docs.continuum.io/anaconda/install#os-x-uninstall
From a post by Robert Martin in comp.object:
Association represents the ability of one instance to send a message to another instance. This is typically implemented with a pointer or reference instance variable, although it might also be implemented as a method argument, or the creation of a local variable.
//[Example:]
//|A|----------->|B|
class A
{
private:
B* itsB;
};
Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).
//[Example:]
//|Node|<>-------->|Node|
class Node
{
private:
vector<Node*> itsNodes;
};
The fact that this is aggregation means that the instances of Node cannot form a cycle. Thus, this is a Tree of Nodes not a graph of Nodes.
Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.
//[Example:]
//|Car|<#>-------->|Carburetor|
class Car
{
public:
virtual ~Car() {delete itsCarb;}
private:
Carburetor* itsCarb
};
There are limitations in PUT over PATCH while making updates. Using PUT requires us to specify all attributes even if we want to change only one attribute. But if we use the PATCH method we can update only the fields we need and there is no need to mention all the fields. PATCH does not allow us to modify a value in an array, or remove an attribute or array entry.
in my case ,the error happened when a lot of concurrent process trying to read/write to the same table. I used retry to workaround the issue
def _retry_if_exception(exception):
return isinstance(exception, Exception)
@retry(retry_on_exception=_retry_if_exception,
wait_random_min=1000,
wait_random_max=5000,
stop_max_attempt_number=5)
def execute(cmd, commit=True):
c.execute(cmd)
c.conn.commit()
The best solution is not to use the same element for column and panel:
<div class="row">
<div class="col-md-3">
<div class="panel" id="gameplay-away-team">Away Team</div>
</div>
<div class="col-md-6">
<div class="panel" id="gameplay-baseball-field">Baseball Field</div>
</div>
<div class="col-md-3">
<div class="panel" id="gameplay-home-team">Home Team</div>
</div>
</div>
and some more styles:
#gameplay-baseball-field {
padding-right: 10px;
padding-left: 10px;
}
DELETE FROM blob
WHERE fileid NOT IN
(SELECT id
FROM files
WHERE id is NOT NULL/*This line is unlikely to be needed
but using NOT IN...*/
)
The accepted answer here gave me unpredictable results, sometimes weirdly adding months and years.
The most reliable way I could find was found here Add days to Javascript Date object, and also increment month
var dayOffset = 20;
var millisecondOffset = dayOffset * 24 * 60 * 60 * 1000;
december.setTime(december.getTime() + millisecondOffset);
EDIT: Even though it has worked for some people, I don't think it is entirely correct. I would recommend going with a more popular answer or using something like http://momentjs.com/
Here's an example using apply
on the dataframe, which I am calling with axis = 1
.
Note the difference is that instead of trying to pass two values to the function f
, rewrite the function to accept a pandas Series object, and then index the Series to get the values needed.
In [49]: df
Out[49]:
0 1
0 1.000000 0.000000
1 -0.494375 0.570994
2 1.000000 0.000000
3 1.876360 -0.229738
4 1.000000 0.000000
In [50]: def f(x):
....: return x[0] + x[1]
....:
In [51]: df.apply(f, axis=1) #passes a Series object, row-wise
Out[51]:
0 1.000000
1 0.076619
2 1.000000
3 1.646622
4 1.000000
Depending on your use case, it is sometimes helpful to create a pandas group
object, and then use apply
on the group.
I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).
Also in Logic Friday the expression A | B
just returns 3 entries in truth table; I expected 4.
#Background
In my case, the error was triggered by changing element tag from to by fault. Inside <TextView an [(ngModel)]="name". was defined.
After removing [(ngModel)]="name" error was gone.
When the WSDL is available, it is just two steps you need to follow to invoke that web service.
Step 1: Generate the client side source from a WSDL2Java
tool
Step 2: Invoke the operation using:
YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();
If you look further, you will notice that the Stub
class is used to invoke the service deployed at the remote location as a web service. When invoking that, your client actually generates the SOAP request and communicates. Similarly the web service sends the response as a SOAP. With the help of a tool like Wireshark, you can view the SOAP messages exchanged.
However since you have requested more explanation on the basics, I recommend you to refer here and write a web service with it's client to learn it further.
Use which(mydata_2$height_chad1 == 2585)
Short example
df <- data.frame(x = c(1,1,2,3,4,5,6,3),
y = c(5,4,6,7,8,3,2,4))
df
x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4
which(df$x == 3)
[1] 4 8
length(which(df$x == 3))
[1] 2
count(df, vars = "x")
x freq
1 1 2
2 2 1
3 3 2
4 4 1
5 5 1
6 6 1
df[which(df$x == 3),]
x y
4 3 7
8 3 4
As Matt Weller pointed out, you can use the length
function.
The count
function in plyr
can be used to return the count of each unique column value.
The difference between an operating system and a kernel:
The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:
There is OpenWebKitSharp, a fork of WebKit.NET 0.5 and very advanced. Details: http://code.google.com/p/open-webkit-sharp/
In .NET 5, a new class has been introduced called JsonContent
, which derives from HttpContent
. See in Microsoft docs
This class has a static method called Create()
, which takes an object as a parameter.
Usage:
var myObject = new
{
foo = "Hello",
bar = "World",
};
JsonContent content = JsonContent.Create(myObject);
HttpResponseMessage response = await _httpClient.PostAsync("https://...", content);
They're two completely different things. ==
compares the object reference, if any, contained by a variable. .equals()
checks to see if two objects are equal according to their contract for what equality means. It's entirely possible for two distinct object instances to be "equal" according to their contract. And then there's the minor detail that since equals
is a method, if you try to invoke it on a null
reference, you'll get a NullPointerException
.
For instance:
class Foo {
private int data;
Foo(int d) {
this.data = d;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
return ((Foo)other).data == this.data;
}
/* In a real class, you'd override `hashCode` here as well */
}
Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances
System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition
Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it
System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything
System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null
If you have an int[], Arrays.toString()
is the easiest way.
You can use this:
addedDate = datetime.now().replace(microsecond=0)
You can select the rows from the table you want to export in the MySQL Workbench SQL Editor. You will find an Export button in the resultset that will allow you to export the records to a CSV file, as shown in the following image:
Please also keep in mind that by default MySQL Workbench limits the size of the resultset to 1000 records. You can easily change that in the Preferences dialog:
Hope this helps.
OK, so what does "best possible solution" mean?
If you mean most readable, then all the possible solutions are pretty much equivalent for an experienced Java programmer. But IMO the most readable is this
public boolean compareStringsOrNulls(String str1, String str2) {
// Implement it how you like
}
In other words, hide the implementation inside a simple method that (ideally) can be inlined.
(You could also "out-source" to a 3rd party utility library ... if you already use it in your codebase.)
If you mean most performant, then:
null
arguments,To add global include path use custom command for qmake in Projects/Build/Build Steps section in "Additional arguments" like this:
"QT+=your_qt_modules" "DEFINES+=your_defines"
I think that you can use any command from *.pro files in that way.
For me the solution was fixing a syntax error:
removing a unwanted semi colon in the angular.module function
private void Add_Click(object sender, EventArgs e) {
OleDbConnection con = new OleDbConnection(@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
cmd.ExecuteNonQuery();
MessageBox.Show("Record Submitted", "Congrats");
con.Close();
}
You need to make sure that your from address is a valid email account setup on that server.
The color you are using is white "#ffffff" is white so try a different one change in the values if you want until you get your need from this link Color Codes and it should go fine
Deprecated features in PHP 5.5.x
The original MySQL extension is now deprecated, and will generate E_DEPRECATED
errors when connecting to a database. Instead, use the **MYSQLi or PDO_MySQL extensions.**
Syntax:
<?php
$connect = mysqli_connect('localhost', 'user', 'password', 'dbname');
Also, replace all mysql_*
functions into mysqli_*
functions
instead of
<?php
$connect = mysql_connect('localhost','root','');
mysql_select_db('dbname');
?>
This CSS2 solution ("any ul
after another ul
") works, too, and is supported by more browsers.
div ul + ul {
background-color: #900;
}
Unlike :not
and :nth-sibling
, the adjacent sibling selector is supported by IE7+.
If you have JavaScript changes these properties after the page loads, you should look at some known bugs in the IE7 and IE8 implementations of this. See this link.
For any static web page, this should work perfectly.
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
About your command line:
root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
You are already authenticated as root
so sudo
is redundant there.
You are missing the -j
or --jump
just before the ACCEPT
parameter (just tought that was a typo and you are inserting it correctly).
About yout question:
If you are inserting the iptables
rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.
If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:
check your vmachine network settings and:
if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.
if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.
if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.
Hope this helps.
raw_input()
takes exactly what the user typed and passes it back as a string.
input()
first takes the raw_input()
and then performs an eval()
on it as well.
The main difference is that input()
expects a syntactically correct python statement where raw_input()
does not.
raw_input()
was renamed to input()
so now input()
returns the exact string.input()
was removed. If you want to use the old input()
, meaning you need to evaluate a user input as a python statement, you have to do it manually by using eval(input())
.
When you declare a variable in javascript, it is assigned the value undefined
. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.
Now you can explicitly assign a variable null
. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.
Now suppose that someone is accessing the middlename variable of your person object and it has the value undefined
. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the value null
, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.
let formelems = document.querySelectorAll('input,textarea,select');
formelems.forEach((formelem) => {
formelem.required = true;
});
If you wish to make all input, textarea, and select elements required.
Generally speaking, fixed section should be set with width
, height
and top
, bottom
properties, otherwise it won't recognise its size and position.
If the used box is direct child for body and has neighbours, then it makes sense to check z-index
and top, left
properties, since they could overlap each other, which might affect your mouse hover while scrolling the content.
Here is the solution for a content box (a direct child of body
tag) which is commonly used along with mobile navigation.
.fixed-content {
position: fixed;
top: 0;
bottom:0;
width: 100vw; /* viewport width */
height: 100vh; /* viewport height */
overflow-y: scroll;
overflow-x: hidden;
}
Hope it helps anybody. Thank you!
In order to make it work, you have to set property GroupName of both radio buttons to the same value:
<asp:RadioButton id="rbMetric" runat="server" GroupName="measurementSystem"></asp:RadioButton>
<asp:RadioButton id="rbUS" runat="server" GroupName="measurementSystem"></asp:RadioButton>
Personally, I prefer to use a RadioButtonList:
<asp:RadioButtonList ID="rblMeasurementSystem" runat="server">
<asp:ListItem Text="Metric" Value="metric" />
<asp:ListItem Text="US" Value="us" />
</asp:RadioButtonList>
Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.
div
has an ID.class
"collapse", this will hide your block by
default. If you want your div to be collapsible AND be shown by
default you need to add "in" class to the collapse. Otherwise the
toggle behavior will not work properly.data-toggle="collapse"
to instruct
Bootstrap to add an appropriate toggle script to this tag.Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
This div (Bar) is shown by default and can toggle
</div>
List<String> list = Arrays.asList("as", "asda", "asd", "urff", "dfkjds", "hfad", "asd", "qadasd", "as", "asda",
"asd", "urff", "dfkjds", "hfad", "asd", "qadasd" + "as", "asda", "asd", "urff", "dfkjds", "hfad", "asd",
"qadasd", "as", "asda", "asd", "urff", "dfkjds", "hfad", "asd", "qadasd");
Method 1:
Set<String> set = new LinkedHashSet<>();
set.addAll(list);
for (String s : set) {
System.out.println(s + " : " + Collections.frequency(list, s));
}
Method 2:
int count = 1;
Map<String, Integer> map = new HashMap<>();
Set<String> set1 = new LinkedHashSet<>();
for (String s : list) {
if (!set1.add(s)) {
count = map.get(s) + 1;
}
map.put(s, count);
count = 1;
}
System.out.println(map);
There are many ways to do what you're asking for:
float
property: <div style="width: 100%; overflow: hidden;">
<div style="width: 600px; float: left;"> Left </div>
<div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
display
property - which can be used to make div
s act like a table
:<div style="width: 100%; display: table;">
<div style="display: table-row">
<div style="width: 600px; display: table-cell;"> Left </div>
<div style="display: table-cell;"> Right </div>
</div>
</div>
_x000D_
There are more methods, but those two are the most popular.
I also had a similar issue. Someone might find what worked for me helpful.
Machine is running Ubuntu 16.04 and has Docker CE. After looking through the answers and links provided here, especially from the link from the Docker website given by Elliot Beach, I opened my /etc/apt/sources.list and examined it.
The file had both deb [arch=amd64] https://download.docker.com/linux/ubuntu (lsb_release -cs) stable
and deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable
.
Since the second one was what was needed, I simply commented out the first, saved the document and now the issue is fixed. As a test, I went back into the same document, removed the comment sign and ran sudo apt-get update
again. The issue returned when I did that.
So to recap : not only did I have my parent Ubuntu distribution name as stated on the Docker website but I also commented out the line still containing (lsb_release -cs).
Declare an array of strings in C++ like this : char array_of_strings[][]
For example : char array_of_strings[200][8192];
will hold 200 strings, each string having the size 8kb or 8192 bytes.
use strcpy(line[i],tempBuffer);
to put data in the array of strings.
My preferred solution (if all strings are numeric only):
// Order by numerical order: (Assertion: all things are numeric strings only)
foreach (var thing in things.OrderBy(int.Parse))
{
Console.Writeline(thing);
}
try this:
SELECT ReportId, Email =
STUFF((SELECT ', ' + Email
FROM your_table b
WHERE b.ReportId = a.ReportId
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId
docker-compose exists to keep you having to write a ton of commands you would have to with docker-cli.
docker-compose also makes it easy to startup multiple containers at the same time and automatically connect them together with some form of networking.
The purpose of docker-compose is to function as docker cli but to issue multiple commands much more quickly.
To make use of docker-compose, you need to encode the commands you were running before into a docker-compose.yml
file.
You are not just going to copy paste them into the yaml file, there is a special syntax.
Once created, you have to feed it to the docker-compose cli and it will be up to the cli to parse the file and create all the different containers with the correct configuration we specify.
So you will have separate containers, let's say, one is redis-server
and the second one is node-app
, and you want that created using the Dockerfile
in your current directory.
Additionally, after making that container, you would map some port from the container to the local machine to access everything running inside of it.
So for your docker-compose.yml
file, you would want to start the first line like so:
version: '3'
That tells Docker the version of docker-compose
you want to use. After that, you have to add:
version: '3'
services:
redis-server:
image: 'redis'
node-app:
build: .
Please notice the indentation, very important. Also, notice for one service I am grabbing an image, but for another service I am telling docker-compose
to look inside the current directory to build the image that will be used for the second container.
Then you want to specify all the different ports that you want open on this container.
version: '3'
services:
redis-server:
image: 'redis'
node-app:
build: .
ports:
-
Please notice the dash, a dash in a yaml file is how we specify an array. In this example, I am mapping 8081
on my local machine to 8081
on the container like so:
version: '3'
services:
redis-server:
image: 'redis'
node-app:
build: .
ports:
- "8081:8081"
So the first port is your local machine, and the other is the port on the container, you could also distinguish between the two to avoid confusion like so:
version: '3'
services:
redis-server:
image: 'redis'
node-app:
build: .
ports:
- "4001:8081"
By developing your docker-compose.yml
file like this, it will create these containers on essentially the same network and they will have free access to communicate with each other any way they please and exchange as much information as they want.
When the two containers are created using docker-compose
, we do not need any port declarations.
Now in my example, we need to do some code configuration in the Nodejs app that looks something like this:
const express = require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient({
host: 'redis-server'
});
I use this example above to make you aware that there may be some specific configuration you would have to do in addition to the docker-compose.yml
file that may be specific to your project.
Now, if you ever find yourself working with a Nodejs app and redis, you want to ensure you are aware of the default port Nodejs uses, so I will add this:
const express = require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient({
host: 'redis-server',
port: 6379
});
So Docker is going to see that the Node app is looking for redis-server
and redirect that connection over to this running container.
The whole time, the Dockerfile
only contains this:
FROM node:alpine
WORKDIR '/app'
COPY /package.json ./
RUN npm install
COPY . .
CMD ["npm", "start"]
So, whereas before you would have to run docker run myimage
to create an instance of all the containers or services inside the file, you can instead run docker-compose up
and you don't have to specify an image because Docker will look in the current working directory and look for a docker-compose.yml
file inside.
Before docker-compose.yml
, we had to deal with two separate commands of docker build .
and docker run myimage
, but in the docker-compose
world, if you want to rebuild your images, you write docker-compose up --build
. That tells Docker to start up the containers again but rebuild it to get the latest changes.
So docker-compose
makes it easier for working with multiple containers. The next time you need to start this group of containers in the background, you can do docker-compose up -d
; and to stop them, you can do docker-compose down
.
If you're on some Linux system, imagemagick is perfect. I.e
convert somefile.png somefile.svg
This works with heaps of different formats.
For other media such as videos and audio use (ffmpeg) I know you clearly stated png to svg, however; It's still media related.
ffmpeg -i somefile.mp3 somefile.ogg
Just a tip for if you wish to go through lots of files; a loop using basic shell tricks..
for f in *.jpg; do convert $f ${f%jpg}png; done
That removes the jpg and adds png which tells convert what you want.
The following script would obtain the ci.jenkins-ci.org public key certificate in base64-encoded DER format and convert it to an OpenSSH public key file. This code assumes that a 2048-bit RSA key is used and draws a lot from this Ian Boyd's answer. I've explained a bit more how it works in comments to this article in Jenkins wiki.
echo -n "ssh-rsa " > jenkins.pub
curl -sfI https://ci.jenkins-ci.org/ | grep -i X-Instance-Identity | tr -d \\r | cut -d\ -f2 | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 >> jenkins.pub
echo >> jenkins.pub
This was driving me crazy, but it seems that aularon's edit was missing the colon after "Vary"
. So changing "Vary Accept-Encoding"
to "Vary: Accept-Encoding"
fixed the issue for me.
I would have commented below the post, but it doesn't seem like it will let me.
Anyhow, I hope this saves someone the same trouble I was having.
Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.
thread apply all bt
window.location.protocol + '//' + window.location.host
I wondered how several of the top answers measured up in terms of speed. I tested the following:
1 @mattbh's
echo "..." | awk '{print $1;}'
2 @ghostdog74's
string="..."; set -- $string; echo $1
3 @boontawee-home's
echo "..." | { read -a array ; echo ${array[0]} ; }
and 4 @boontawee-home's
echo "..." | { read first _ ; echo $first ; }
I measured them with Python's timeit in a Bash script in a Zsh terminal on macOS, using a test string with 215 5-letter words. Did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:
method time
--------------------------------
1. awk 9.2ms
2. set 11.6ms (1.26 * "1")
3. read -a 11.7ms (1.27 * "1")
4. read 13.6ms (1.48 * "1")
Nice job, voters The votes (as of this writing) match the solutions' speed!
With Grid
A pretty simpel and modern way is to use display: grid
div {
border: 1px dotted grey;
}
#outer {
display: grid;
place-items: center;
height: 50px; /* not necessary */
}
_x000D_
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="outer">
<div>Foo foo</div>
</div>
</body>
</html>
_x000D_
There is no need to remove any .iml
files. Follow this:
File
->
Open...
and choose your newly created build.gradle
Open Existing Project
Delete Existing Project and Import
You want to use an absolute path to the executable, and use the cwd
kwarg of Popen
to set the working directory. See the docs.
If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.
FRP is a combination of Functional programming(programming paradigm built upon the idea of everything is a function) and reactive programming paradigm (built upon the idea that everything is a stream(observer and observable philosophy)). It is supposed to be the best of the worlds.
Check out Andre Staltz post on reactive programming to start with.
As everyone has pointed out, use the -S
option to GCC. I would also like to add that the results may vary (wildly!) depending on whether or not you add optimization options (-O0
for none, -O2
for agressive optimization).
On RISC architectures in particular, the compiler will often transform the code almost beyond recognition in doing optimization. It's impressive and fascinating to look at the results!
Note (Oct 2020): AsyncTask used in the following answer has been deprecated in Android API level 30. Please refer to Official documentation or this blog post for a more updated example
Updated (June 2017) Answer which works on Android 6.0+. Thanks to @Rohit Suthar, @Tamis Bolvari and @sudhiskr for the comments.
public class CallAPI extends AsyncTask<String, String, String> {
public CallAPI(){
//set context variables if required
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String urlString = params[0]; // URL to call
String data = params[1]; //data to post
OutputStream out = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
References:
Original Answer (May 2010)
Note: This solution is outdated. It only works on Android devices up to 5.1. Android 6.0 and above do not include the Apache http client used in this answer.
Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Another approach is to use the first_value
window function: http://sqlfiddle.com/#!12/7a145/14
SELECT DISTINCT
first_value("id") OVER (PARTITION BY "category" ORDER BY "date" DESC)
FROM Table1
ORDER BY 1;
... though I suspect hims056's suggestion will typically perform better where appropriate indexes are present.
A third solution is:
SELECT
id
FROM (
SELECT
id,
row_number() OVER (PARTITION BY "category" ORDER BY "date" DESC) AS rownum
FROM Table1
) x
WHERE rownum = 1;
For spring :
File inputFile = new ClassPathResource("\\chrome\\chromedriver.exe").getFile();
System.setProperty("webdriver.chrome.driver",inputFile.getCanonicalPath());
Additional to nanselm2's answer, you can use 0
instead of False
:
df["col"].str.contains(word)==0
If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:
@keyframes changewidth {
from {
transform: scaleX(1);
}
to {
transform: scaleX(2);
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108
I prefer to use:
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
What does ToFileTime() do?
Converts the value of the current DateTime object to a Windows file time.
public long ToFileTime()
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.
For people arriving here looking for an answer to a more generic question, you can extend the static class concept if you want your code to look like an enum
.
The following approach works when you haven't finalised the enum names
you want and the enum values
are the string
representation of the enam name
; use nameof()
to make your refactoring simpler.
public static class Colours
{
public static string Red => nameof(Red);
public static string Green => nameof(Green);
public static string Blue => nameof(Blue);
}
This achieves the intention of an enum that has string values (such as the following pseudocode):
public enum Colours
{
"Red",
"Green",
"Blue"
}
=
can be used when the subquery returns only 1 value.
When subquery returns more than 1 value, you will have to use IN
:
select *
from table
where id IN (multiple row query);
For example:
SELECT *
FROM Students
WHERE Marks = (SELECT MAX(Marks) FROM Students) --Subquery returns only 1 value
SELECT *
FROM Students
WHERE Marks IN
(SELECT Marks
FROM Students
ORDER BY Marks DESC
LIMIT 10) --Subquery returns 10 values
Or this:
Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
Order1:=xlAscending, Header:=xlYes
I would use a varchar(22). Big enough to hold a north american phone number with extension. You would want to strip out all the nasty '(', ')', '-' characters, or just parse them all into one uniform format.
Alex
Like andynormancx' post, use this (if you're working in an Unix environment):
scriptname > /dev/null
Or you can use this (if you're working in a Windows environment):
scriptname > nul
When you access resultFrame through document.all it only pulls it as an HTML element, not a window frame. You get the same issue if you have a frame fire an event using a "this" self-reference.
Replace:
document.all.resultFrame.Reset();
With:
window.frames.resultFrame.Reset();
Or:
document.all.resultFrame.contentWindow.Reset();
The above problem can also be solved using ConstraintLayout through Guidelines.
Below is the snippet.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.constraint.Guideline
android:id="@+id/upperGuideLine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.68" />
<Gallery
android:id="@+id/gallery"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/lowerGuideLine"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/upperGuideLine" />
<android.support.constraint.Guideline
android:id="@+id/lowerGuideLine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.84" />
</android.support.constraint.ConstraintLayout>
You need to find (or define) a 'get' template tag, for example, here.
The tag definition:
@register.filter
def hash(h, key):
return h[key]
And it’s used like:
{% for o in objects %}
<li>{{ dictionary|hash:o.id }}</li>
{% endfor %}
▐▐ is HTML and is made with this code: ▐▐
.
I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.
The solution if datetime doesn't support %f and without needing a try/except is:
(dt, mSecs) = row[5].strip().split(".")
dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
mSeconds = datetime.timedelta(microseconds = int(mSecs))
fullDateTime = dt + mSeconds
This works for the input string "2010-10-06 09:42:52.266000"
MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.
Using compare methods like so:
<?php
$db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
$my_pass = "mypass";
if ($db_pass === md5($my_pass)) {
// password is matched
} else {
// password didn't match
}
Only for WordPress users.
If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass
is not only MD5 format it also uses utf8_mb4_cli
charset so what to do?
That's why I use another Approach if I forget my WordPress password I use
I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )
EASY is use this :
I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS
WORDPRESS USE THIS
https://developer.wordpress.org/reference/functions/wp_hash_password/
Can be done in major new broswers using the code below
.img {
-webkit-filter:invert(100%);
filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1');
}
However, if you want it to work across all browsers you need to use Javascript. Something like this gist will do the job.
I had a similar problem (using 3.5) and lost 1/2 a day to it but here is a something that works - I am retired and just learning Python so I can help my grandson (12) with it.
mydict2={'Atlanta':78,'Macon':85,'Savannah':72}
maxval=(max(mydict2.values()))
print(maxval)
mykey=[key for key,value in mydict2.items()if value==maxval][0]
print(mykey)
YEILDS;
85
Macon
You can setup global parameter with
jQuery.ajaxSettings.traditional = true;
A concise way is to use a tuple as key-value pair:
const keyVal: [string, string] = ["key", "value"] // explicit type
// or
const keyVal2 = ["key", "value"] as const // inferred type with const assertion
[key, value]
tuples also ensure compatibility to JS built-in objects:
Object
, esp. Object.entries
, Object.fromEntries
Map
, esp. Map.prototype.entries
and new Map()
constructorSet
, esp. Set.prototype.entries
You can create a generic KeyValuePair
type for reusability:
type KeyValuePair<K extends string | number, V = unknown> = [K, V]
const kv: KeyValuePair<string, string> = ["key", "value"]
Upcoming TS 4.0 provides named/labeled tuples for better documentation and tooling support:
type KeyValuePairNamed = [key: string, value: string] // add `key` and `value` labels
const [key, val]: KeyValuePairNamed = ["key", "val"] // array destructuring for convenience
You may actually go with ViewChild API
...
parent.ts
<button (click)="clicked()">click</button>
export class App {
@ViewChild(Child) vc:Child;
constructor() {
this.name = 'Angular2'
}
func(e) {
console.log(e)
}
clicked(){
this.vc.getName();
}
}
child.ts
export class Child implements OnInit{
onInitialized = new EventEmitter<Child>();
...
...
getName()
{
console.log('called by vc')
console.log(this.name);
}
}
Looks like you runs out of swap memory, try this
/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1
as mentioned by @BlackBurn027 on comments below, this solution was described in here
You are exceeding the length of int datatype. You can use UNSIGNED attribute to support that value.
SIGNED INT can support till 2147483647 and with UNSIGNED INT allows double than this. After this you still want to save data than use CHAR or VARCHAR with length 10
dividend % divisor
Dividend is the numeric expression to divide. Dividend must be any expression of integer data type in sql server.
Divisor is the numeric expression to divide the dividend. Divisor must be expression of integer data type except in sql server.
SELECT 15 % 2
Output
1
Dividend = 15
Divisor = 2
Let's say you wanted to query
Query a list of CITY names from STATION with even ID numbers only.
Schema structure for STATION:
ID Number
CITY varchar
STATE varchar
select CITY from STATION as st where st.id % 2 = 0
Will fetch the even set of records
In order to fetch the odd records with Id as odd number.
select CITY from STATION as st where st.id % 2 <> 0
% function reduces the value to either 0 or 1
The same problem occurred when working on XCode 9 using Swift 4.
Add AutoLayout for the UI elements inside the Cell and custom cell row height will work accordingly as specified.
Step 1: create a MANIFEST.in
file in the same folder with setup.py
Step 2: include the relative path to the files you want to add in MANIFEST.in
include README.rst
include docs/*.txt
include funniest/data.json
Step 3: set include_package_data=True
in the setup()
function to copy these files to site-package
If you use jCanvas library you can use opacity property when drawing. If you need fade effect on top of that, simply redraw with different values.
For Python 3 and above,To select first n Pairs
n=4
firstNpairs = {k: Diction[k] for k in list(Diction.keys())[:n]}
Since you are learning Git, know that this has little to do with git but with the text editor configured for use. In vim, you can press i
to start entering text and save by pressing esc
and :wq
and enter
, this will commit with the message you typed. In your current state, to just come out without committing, you can do :q
instead of the :wq
as mentioned above.
Alternatively, you can just do git commit -m '<message>'
instead of having git open the editor to type the message.
Note that you can also change the editor and use something you are comfortable with ( like notepad) - How can I set up an editor to work with Git on Windows?
When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.
However, when GROUP BY is used:
Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.
Check this
UPDATE some_table SET some_field = REPLACE("Column Name/String", 'Search String', 'Replace String')
Eg with sample string:
UPDATE some_table SET some_field = REPLACE("this is test string", 'test', 'sample')
EG with Column/Field Name:
UPDATE some_table SET some_field = REPLACE(columnName, 'test', 'sample')
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
I want to work with exec_query
of the ActiveRecord
class, because it returns the mapping of the query transforming into object, so it gets very practical and productive to iterate with the objects when the subject is Raw SQL.
Example:
values = ActiveRecord::Base.connection.exec_query("select * from clients")
p values
and return this complete query:
[{"id": 1, "name": "user 1"}, {"id": 2, "name": "user 2"}, {"id": 3, "name": "user 3"}]
To get only list of values
p values.rows
[[1, "user 1"], [2, "user 2"], [3, "user 3"]]
To get only fields columns
p values.columns
["id", "name"]
Assuming you already have a application created under google developer console, Follow the below steps
https://console.cloud.google.com/apis/dashboard?
you will be getting the below page Note: Please use a server to load the html
file