Sharing my methods in case someone needs them:
/** Determines if the context calling has the required permission
* @param context - the IPC context
* @param permissions - The permissions to check
* @return true if the IPC has the granted permission
*/
public static boolean hasPermission(Context context, String permission) {
int res = context.checkCallingOrSelfPermission(permission);
Log.v(TAG, "permission: " + permission + " = \t\t" +
(res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED"));
return res == PackageManager.PERMISSION_GRANTED;
}
/** Determines if the context calling has the required permissions
* @param context - the IPC context
* @param permissions - The permissions to check
* @return true if the IPC has the granted permission
*/
public static boolean hasPermissions(Context context, String... permissions) {
boolean hasAllPermissions = true;
for(String permission : permissions) {
//you can return false instead of assigning, but by assigning you can log all permission values
if (! hasPermission(context, permission)) {hasAllPermissions = false; }
}
return hasAllPermissions;
}
And to call it:
boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] {
android.Manifest.permission.ACCESS_WIFI_STATE,
android.Manifest.permission.READ_PHONE_STATE,
android.Manifest.permission.ACCESS_NETWORK_STATE,
android.Manifest.permission.INTERNET,
});
Symfony 2.7 has a new absolute_url which can be used to generate the absolute url. http://symfony.com/blog/new-in-symfony-2-7-the-new-asset-component#template-function-changes
It will work on those both cases or a path string:
<a href="{{ absolute_url(path('route_name', {'param' : value})) }}">A link</a>
and for assets:
<img src="{{ absolute_url(asset('bundle/myname/img/image.gif')) }}" alt="Title"/>
Or for any string path
<img src="{{ absolute_url('my/absolute/path') }}" alt="Title"/>
on those tree cases you will end up with an absolute URL like
http://www.example.com/my/absolute/path
I know I'm late to the party but I thought I'd add what I ended up using for this - which is to simply check if the file upload input does not contain a truthy value with the not operator & JQuery like so:
if (!$('#videoUploadFile').val()) {
alert('Please Upload File');
}
Note that if this is in a form, you may also want to wrap it with the following handler to prevent the form from submitting:
$(document).on("click", ":submit", function (e) {
if (!$('#videoUploadFile').val()) {
e.preventDefault();
alert('Please Upload File');
}
}
This is an old post but I have issues with coming across posts that have some incorrect information/syntax...
If you wanted to do this with a shorcut icon you could just create a shortcut on your desktop for the cmd.exe application. Then append a /K {your command} to the shorcut path.
So a default shorcut target path may look like "%windir%\system32\cmd.exe", just change it to %windir%\system32\cmd.exe /k {commands}
example: %windir%\system32\cmd.exe /k powercfg -lastwake
In this case i would use /k (keep open) to display results.
Arlen was right about the /k (keep open) and /c (close)
You can open a command prompt and type "cmd /?" to see your options.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true
A batch file is kind of overkill for a single command prompt command...
Hope this helps someone else
Try setting the HOME environment variable in Windows to your home folder (c:\users\username
).
( you can confirm that this is the problem by doing echo $HOME
in git bash and echo %HOME%
in cmd - latter might not be available )
Maven working terminology having phases and goals.
Phase:Maven phase is a set of action which is associated with 2 or 3 goals
exmaple:- if you run mvn clean
this is the phase will execute the goal mvn clean:clean
Goal:Maven goal bounded with the phase
for reference http://books.sonatype.com/mvnref-book/reference/lifecycle-sect-structure.html
I was also having same issue and stuck for some days, but after some research i figured out that we can actually use chrome's "--remote-debugging-port" to intercept requests in conjunction with selenium web driver. Use following Pseudocode as a reference:-
create instance of chrome driver with remote debugging
int freePort = findFreePort();
chromeOptions.addArguments("--remote-debugging-port=" + freePort);
ChromeDriver driver = new ChromeDriver(chromeOptions);`
make a get call to http://127.0.0.1:freePort
String response = makeGetCall( "http://127.0.0.1" + freePort + "/json" );
Extract chrome's webSocket Url to listen, you can see response and figure out how to extract
String webSocketUrl = response.substring(response.indexOf("ws://127.0.0.1"), response.length() - 4);
Connect to this socket, u can use asyncHttp
socket = maketSocketConnection( webSocketUrl );
Enable network capture
socket.send( { "id" : 1, "method" : "Network.enable" } );
Now chrome will send all network related events and captures them as follows
socket.onMessageReceived( String message ){
Json responseJson = toJson(message);
if( responseJson.method == "Network.responseReceived" ){
//extract status code
}
}
driver.get("http://stackoverflow.com");
you can do everything mentioned in dev tools site. see https://chromedevtools.github.io/devtools-protocol/ Note:- use chromedriver 2.39 or above.
I hope it helps someone.
reference : Using Google Chrome remote debugging protocol
Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
PATH=$PATH:.
Just make sure to add Shebang (#!/bin/bash
) line at the starting of your script and make the script executable(using chmod +x <File Name>
).
for php version 5.2.17 __DIR__
will not work it will only works with php 5.3
But for older version of php dirname(__FILE__)
perfectly
For example write like this
require_once dirname(__FILE__) . '/db_config.php';
We encountered this error after an upgrade from 2008 to 2014 SQL Server where our some of our previous connection strings for local development had a Data Source=./ like this
<add name="MyLocalDatabase" connectionString="Data Source=./;Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>
Changing that from ./ to either (local) or localhost fixed the problem.
<add name="MyLocalDatabase" connectionString="Data Source=(local);Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>
This code should work reasonably well:
public static File createTempDir() {
final String baseTempPath = System.getProperty("java.io.tmpdir");
Random rand = new Random();
int randomInt = 1 + rand.nextInt();
File tempDir = new File(baseTempPath + File.separator + "tempDir" + randomInt);
if (tempDir.exists() == false) {
tempDir.mkdir();
}
tempDir.deleteOnExit();
return tempDir;
}
I have the same issue for managing account settings as name value pairs. The design criteria is that different clients could have different settings sets.
My solution, similar to JWP is to bulk erase and replace, generating the merge record within your application.
This is pretty bulletproof, platform independent and since there are never more than about 20 settings per client, this is only 3 fairly low load db calls - probably the fastest method.
The alternative of updating individual rows - checking for exceptions then inserting - or some combination of is hideous code, slow and often breaks because (as mentioned above) non standard SQL exception handling changing from db to db - or even release to release.
#This is pseudo-code - within the application:
BEGIN TRANSACTION - get transaction lock
SELECT all current name value pairs where id = $id into a hash record
create a merge record from the current and update record
(set intersection where shared keys in new win, and empty values in new are deleted).
DELETE all name value pairs where id = $id
COPY/INSERT merged records
END TRANSACTION
You can use the fromstring()
method for this:
arr = np.array([1, 2, 3, 4, 5, 6])
ts = arr.tostring()
print(np.fromstring(ts, dtype=int))
>>> [1 2 3 4 5 6]
Sorry for the short answer, not enough points for commenting. Remember to state the data types or you'll end up in a world of pain.
Note on fromstring
from numpy 1.14 onwards:
sep : str, optional
The string separating numbers in the data; extra whitespace between elements is also ignored.
Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results.
You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:
Set MyEmail=CreateObject("CDO.Message")
MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"
'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
MyEmail.Configuration.Fields.Update
MyEmail.Send
set MyEmail=nothing
If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update
line:
'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username"
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"
More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm
If you wanted that sort of functionality you would need to override it in your activity, and then add a YourBackPressed
interface to all your fragments, which you call on the relevant fragment whenever the back button is pressed.
Edit: I'd like to append my previous answer.
If I were to do this today, I'd use a broadcast, or possibly a ordered broadcast if I expected other panels to update in unison to the master/main content panel.
LocalBroadcastManager
in the Support Library can help with this, and you just send the broadcast in onBackPressed
and subscribe in your fragments that care. I think that Messaging is a more decoupled implementation and would scale better, so it would be my official implementation recommendation now. Just use the Intent
's action as a filter for your message. send your newly created ACTION_BACK_PRESSED
, send it from your activity and listen for it in the relevant fragments.
You need to go into the developer console and set
http://localhost:8080/WEBAPP/youtube-callback.html
as your callback URL.
This video is slightly outdated, as it shows the older Developer Console instead of the new one, however, the concepts should still apply. You need to find your project in the developer console and register a callback URL.
It does not matter where the variable comes from. Main thing we have one ... Set the variable name between square brackets "[ .. ]".
var optionName = 'nameA';
var JsonVar = {
[optionName] : 'some value'
}
instead of...
$(".class").click( function() {
// do something
});
You can write...
$('body').on('click', '.class', function() {
// do something
});
Just a small correction for Marko's answer: exact number can't be produced out of some general calculations straight forward due to the next fact: Valid IP addresses should also not end with binary 0 or 1 sequences that have same length as zero sequence in subnet mask. So the final answer really depends on the total number of subnets (Marko's answer - 2 * total subnet count).
I was trying to use aws-vault which uses pass and gnugp2 (gpg2). I'm on Ubuntu 20.04 running in WSL2.
I tried all the solutions above, and eventually, I had to do one more thing -
$ rm ~/.gnupg/S.* # remove cache
$ gpg-connect-agent reloadagent /bye # restart gpg agent
$ export GPG_TTY=$(tty) # prompt for password
# ^ This last line should be added to your ~/.bashrc file
The source of this solution is from some blog-post in Japanese, luckily there's Google Translate :)
CHARINDEX
will return 0
if no spaces are in the string and then you look for a substring of -1
length.
You can tack a trailing space on to the end of the string to ensure there is always at least one space and avoid this problem.
SELECT SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode + ' ' ) -1)
Premising that those are two distinct properties, in your specific example there's no difference in the result, since background
actually is a shorthand for
background-color background-image background-position background-repeat background-attachment background-clip background-origin background-size
Thus, besides the background-color
, using the background
shorthand you could also add one or more values without repeating any other background-*
property more than once.
Which one to choose is essentially up to you, but it could also depend on specific conditions of your style declarations (e.g if you need to override just the background-color
when inheriting other related background-*
properties from a parent element, or if you need to remove all the values except the background-color
).
Git has two types of branches: local
and remote
. To use git pull
and git push
as you'd like, you have to tell your local branch (my_test
) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.
Commands
Make sure you're on your master
branch with
1)git checkout master
then create the new branch with
2)git branch --track my_test origin/my_test
and check it out with
3)git checkout my_test
.
You can then push
and pull
without specifying which local and remote.
However if you've already created the branch then you can use the -u
switch to tell git's push
and pull
you'd like to use the specified local and remote branches from now on, like so:
git pull -u my_test origin/my_test
git push -u my_test origin/my_test
Config
The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config
and add the following to the bottom.
[remote "origin"]
url = [email protected]:username/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
remote = origin
merge = refs/heads/my_test
This specifies a remote called origin
, in this case a GitHub style one, and then tells the branch my_test
to use it as it's remote.
You can find something very similar to this in the config after running the commands above.
Some useful resources:
I use these defines:
/** Use to init the clock */
#define TIMER_INIT \
LARGE_INTEGER frequency; \
LARGE_INTEGER t1,t2; \
double elapsedTime; \
QueryPerformanceFrequency(&frequency);
/** Use to start the performance timer */
#define TIMER_START QueryPerformanceCounter(&t1);
/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP \
QueryPerformanceCounter(&t2); \
elapsedTime=(float)(t2.QuadPart-t1.QuadPart)/frequency.QuadPart; \
std::wcout<<elapsedTime<<L" sec"<<endl;
Usage (brackets to prevent redefines):
TIMER_INIT
{
TIMER_START
Sleep(1000);
TIMER_STOP
}
{
TIMER_START
Sleep(1234);
TIMER_STOP
}
Output from usage example:
1.00003 sec
1.23407 sec
>>> mask = df['ids'].str.contains('ball')
>>> mask
0 True
1 True
2 False
3 True
Name: ids, dtype: bool
>>> df[mask]
ids vals
0 aball 1
1 bball 2
3 fball 4
To bash into a running container, type this:
docker exec -t -i container_name /bin/bash
or
docker exec -ti container_name /bin/bash
or
docker exec -ti container_name sh
Assuming your 'time' column has at least one observation with a non-numeric character and all your other columns only have numbers, then 'read.csv's default will be to read in 'time' as a 'factor' and all the rest of the columns as 'numeric'. Therefore setting 'stringsAsFactors=F' will have the same result as setting the 'colClasses' manually i.e.,
data <- read.csv('test.csv', stringsAsFactors=F)
Yes with reflection. This works (based on this answer):
(Note: this is a workaround due to lack of support for custom fonts, so if you want to change this situation please do star to up-vote the android issue here). Note: Do not leave "me too" comments on that issue, everyone who has stared it gets an email when you do that. So just "star" it please.
import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;
public final class FontsOverride {
public static void setDefaultFont(Context context,
String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName,
final Typeface newTypeface) {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
You then need to overload the few default fonts, for example in an application class:
public final class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
}
}
Or course if you are using the same font file, you can improve on this to load it just once.
However I tend to just override one, say "MONOSPACE"
, then set up a style to force that font typeface application wide:
<resources>
<style name="AppBaseTheme" parent="android:Theme.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
</resources>
I've investigated the reports in the comments that it doesn't work and it appears to be incompatible with the theme android:Theme.Material.Light
.
If that theme is not important to you, use an older theme, e.g.:
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:typeface">monospace</item>
</style>
The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.
Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true
will not work with your first method.
Just write a static method in Util class. I am reading a Json from a file. you can give String also to readValue
public static <T> T convertJsonToPOJO(String filePath, Class<?> target) throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(new File(filePath), objectMapper .getTypeFactory().constructCollectionType(List.class, Class.forName(target.getName())));
}
Usage:
List<TaskBean> list = Util.<List<TaskBean>>convertJsonToPOJO("E:/J2eeWorkspaces/az_workspace_svn/az-client-service/dir1/dir2/filename.json", TaskBean.class);
After researching everywhere finally i have found out temporary solution. Because i have try all the solution installing access drivers but still i am facing same issues.
For excel source, Before this step you need to change the setting. Save excel file as 2010 format.xlsx
Also set Project Configuration Properties for Debugging Run64BitRuntime = False
I am using visual studio 2017, sql server 2017, office 2016, and Microsoft access database 2010 engine 32bit. Os windows 10 64 bit.
This is temporary solution. Because many peoples are searching for this type of question. Finally I figured out and this solution is not available in any of the website.
When you specify:
psql -U user
it connects via UNIX Socket, which by default uses peer
authentication, unless specified in pg_hba.conf
otherwise.
You can specify:
host database user 127.0.0.1/32 md5
host database user ::1/128 md5
to get TCP/IP connection on loopback interface (both IPv4 and IPv6) for specified database
and user
.
After changes you have to restart postgres or reload it's configuration. Restart that should work in modern RHEL/Debian based distros:
service postgresql restart
Reload should work in following way:
pg_ctl reload
but the command may differ depending of PATH configuration - you may have to specify absolute path, which may be different, depending on way the postgres was installed.
Then you can use:
psql -h localhost -U user -d database
to login with that user
to specified database
over TCP/IP.
md5
stands for encrypted password, while you can also specify password
for plain text passwords during authorisation. These 2 options shouldn't be of a great matter as long as database server is only locally accessible, with no network access.
Important note:
Definition order in pg_hba.conf
matters - rules are read from top to bottom, like iptables, so you probably want to add proposed rules above the rule:
host all all 127.0.0.1/32 ident
Try giving your divs a width of 100%
.
Git Stash Pop vs apply
Working
If you want to apply your top stashed changes to current non-staged change and delete that stash as well, then you should go for git stash pop
.
# apply the top stashed changes and delete it from git stash area.
git stash pop
But if you are want to apply your top stashed changes to current non-staged change without deleting it, then you should go for git stash apply
.
Note : You can relate this case with
Stack
classpop()
andpeek()
methods, where pop change the top by decrements (top = top-1) butpeek()
only able to get the top element.
You can't put a div
directly inside a table
, like this:
<!-- INVALID -->
<table>
<div>
Hello World
</div>
</table>
Putting a div
inside a td
or th
element is fine, however:
<!-- VALID -->
<table>
<tr>
<td>
<div>
Hello World
</div>
</td>
</tr>
</table>
# As long as there is at least one more argument, keep looping
while [[ $# -gt 0 ]]; do
key="$1"
case "$key" in
# This is a flag type option. Will catch either -f or --foo
-f|--foo)
FOO=1
;;
# Also a flag type option. Will catch either -b or --bar
-b|--bar)
BAR=1
;;
# This is an arg value type option. Will catch -o value or --output-file value
-o|--output-file)
shift # past the key and to the value
OUTPUTFILE="$1"
;;
# This is an arg=value type option. Will catch -o=value or --output-file=value
-o=*|--output-file=*)
# No need to shift here since the value is part of the same string
OUTPUTFILE="${key#*=}"
;;
*)
# Do whatever you want with extra options
echo "Unknown option '$key'"
;;
esac
# Shift after checking all the cases to get the next option
shift
done
This allows you to have both space separated options/values, as well as equal defined values.
So you could run your script using:
./myscript --foo -b -o /fizz/file.txt
as well as:
./myscript -f --bar -o=/fizz/file.txt
and both should have the same end result.
PROS:
Allows for both -arg=value and -arg value
Works with any arg name that you can use in bash
Pure bash. No need to learn/use getopt or getopts
CONS:
Can't combine args
on the basis of your only jQuery
tag :)
HTML
<select id="my-select">
<option value="1">This is text 1</option>
<option value="2">This is text 2</option>
<option value="3">This is text 3</option>
</select>
For text --
$(document).ready(function() {
$("#my-select").change(function() {
alert($('#my-select option:selected').html());
});
});
For value --
$(document).ready(function() {
$("#my-select").change(function() {
alert($(this).val());
});
});
What if:
<asp:Button ID="Button1" runat="server" CssClass="test1 test3 test-test" />
To add or remove a class, instead of overwriting all classes with
BtnventCss.CssClass = "hom_but_a"
keep the HTML correct:
string classname = "TestClass";
// Add a class
BtnventCss.CssClass = String.Join(" ", Button1
.CssClass
.Split(' ')
.Except(new string[]{"",classname})
.Concat(new string[]{classname})
.ToArray()
);
// Remove a class
BtnventCss.CssClass = String.Join(" ", Button1
.CssClass
.Split(' ')
.Except(new string[]{"",classname})
.ToArray()
);
This assures
Especially when client-side development is using several classnames on one element.
In your example, use
string classname = "TestClass";
// Add a class
Button1.Attributes.Add("class", String.Join(" ", Button1
.Attributes["class"]
.Split(' ')
.Except(new string[]{"",classname})
.Concat(new string[]{classname})
.ToArray()
));
// Remove a class
Button1.Attributes.Add("class", String.Join(" ", Button1
.Attributes["class"]
.Split(' ')
.Except(new string[]{"",classname})
.ToArray()
));
You should wrap this in a method/property ;)
You can only return one value, but it can be an object that has multiple fields - ie a "value object". Eg
public class MyResult {
int returnCode;
String errorMessage;
// etc
}
public MyResult someMethod() {
// impl here
}
This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.
I combined some beautiful answers here to make it possible to easily support more Expression operators.
This is based on the answer of @Dejan but now it's quite easy to add the OR as well. I chose not to make the Combine
function public, but you could do that to be even more flexible.
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.AndAlso);
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.Or);
public static Expression<Func<T, bool>> Combine<T>(Expression<Func<T, bool>> leftExpression, Expression<Func<T, bool>> rightExpression, Func<Expression, Expression, BinaryExpression> combineOperator)
{
var leftParameter = leftExpression.Parameters[0];
var rightParameter = rightExpression.Parameters[0];
var visitor = new ReplaceParameterVisitor(rightParameter, leftParameter);
var leftBody = leftExpression.Body;
var rightBody = visitor.Visit(rightExpression.Body);
return Expression.Lambda<Func<T, bool>>(combineOperator(leftBody, rightBody), leftParameter);
}
private class ReplaceParameterVisitor : ExpressionVisitor
{
private readonly ParameterExpression _oldParameter;
private readonly ParameterExpression _newParameter;
public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
{
_oldParameter = oldParameter;
_newParameter = newParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return ReferenceEquals(node, _oldParameter) ? _newParameter : base.VisitParameter(node);
}
}
}
Usage is not changed and still like this:
Expression<Func<Result, bool>> noFilterExpression = item => filters == null;
Expression<Func<Result, bool>> laptopFilterExpression = item => item.x == ...
Expression<Func<Result, bool>> dateFilterExpression = item => item.y == ...
var combinedFilterExpression = noFilterExpression.Or(laptopFilterExpression.AndAlso(dateFilterExpression));
efQuery.Where(combinedFilterExpression);
(This is an example based on my actual code, but read is as pseudo-code)
http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
Thanks @gunar, but I think there is a better way.
According to doc :
* If you are committing a single transaction that does not modify the * fragment back stack, strongly consider using * {@link FragmentTransaction#commitNow()} instead. This can help avoid * unwanted side effects when other code in your app has pending committed * transactions that expect different timing. * * @return Returns true if there were any pending transactions to be * executed. */ public abstract boolean executePendingTransactions();
So use commitNow
to replace:
fragmentTransaction.commit();
FragmentManager.executePendingTransactions()
You should use the Spring Boot Maven Plugin:
<project>
...
<build>
...
<plugins>
...
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.1.RELEASE</version>
<configuration>
<profiles>
<profile>foo</profile>
<profile>bar</profile>
</profiles>
</configuration>
...
</plugin>
...
</plugins>
...
</build>
...
</project>
I added @Component
annotation from import org.springframework.stereotype.Component
and the problem was solved.
Is solved this using RouteValueDictionary (works fine as htmlAttributes as it's based on IDictionary) and an extension method:
public static RouteValueDictionary AddIf(this RouteValueDictionary dict, bool condition, string name, object value)
{
if (condition) dict.Add(name, value);
return dict;
}
Usage:
@Html.TextBoxFor(m => m.GovId, new RouteValueDictionary(new { @class = "form-control" })
.AddIf(Model.IsEntityFieldsLocked, "disabled", "disabled"))
Credit goes to https://stackoverflow.com/a/3481969/40939
I use the little utility which comes with PureMPI.net called execcmd.exe
. Its syntax is as follows:
execcmd \\yourremoteserver <your command here>
Doesn't get any simpler than this :)
Anyway, we have a "goes to" operator now. "-->"
is easy to be remembered as a direction, and "while x goes to zero" is meaning-straight.
Furthermore, it is a little more efficient than "for (x = 10; x > 0; x --)"
on some platforms.
The default for matrix
is to have 1 column. To explicitly have 0 columns, you need to write
matrix(, nrow = 15, ncol = 0)
A better way would be to preallocate the entire matrix and then fill it in
mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
mat[, column] <- vector
}
I don't how this works, but it worked.
$post_data = json_decode(json_encode($_POST['request_key']));
Non-blocking: This function won't wait while on the stack.
Asynchronous: Work may continue on behalf of the function call after that call has left the stack
Node.js:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
Browser (webapi):
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
When there is a need to restrict access to some functions, we'll use the static keyword while defining and declaring a function.
/* file ab.c */
static void function1(void)
{
puts("function1 called");
}
And store the following code in another file ab1.c
/* file ab1.c */
int main(void)
{
function1();
getchar();
return 0;
}
/* in this code, we'll get a "Undefined reference to function1".Because function 1 is declared static in file ab.c and can't be used in ab1.c */
I think the easiest way to do it is by styling a label
and making the checkbox
invisible.
HTML
<input type="checkbox" id="first" />
<label for="first"> </label>
CSS
checkbox {
display: none;
}
checkbox + label {
/* Style for checkbox normal */
width: 16px;
height: 16px;
}
checkbox::checked + label,
label.checked {
/* Style for checkbox checked */
}
The checkbox
, even though it is hidden, will still be accessible, and its value will be sent when a form is submitted. For old browsers you might have to change the class of the label
to checked using JavaScript because I don't think old versions of Internet Explorer understand ::checked
on the checkbox
.
A simple SQL example would be like this:
ALTER TABLE `<table_name>` ADD `<column_name>` INT(11) NULL DEFAULT NULL ;
Make sure you use back ticks `` in table name and column name
On the other hand, if you are only working on java source and are getting these errors from stuff you don't touch in a large project that is working, you can just turn off the validations in Eclipse. The settings are under Preferences->Web->JSP Files->Validation
One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.
PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.
pip install py-mini-racer
from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
return a+c+b;
}
""")
ctx.call("escramble_758")
And yes, you have to replace document.write
with return
as others suggested
Get Boost ! : -)
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <vector>
using namespace std;
using namespace boost;
int main(int argc, char**argv) {
typedef vector < string > list_type;
list_type list;
string line;
line = "Somewhere down the road";
split(list, line, is_any_of(" "));
for(int i = 0; i < list.size(); i++)
{
cout << list[i] << endl;
}
return 0;
}
This example gives the output -
Somewhere
down
the
road
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-
inline-elements :- <img style="vertical-align:middle" ...>
<span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>
block-elements :- <td style="vertical-align:middle"> ... </td>
<div style="display:table-cell; vertical-align:middle"> ... </div>
see the demo:- http://jsfiddle.net/Ewfkk/2/
I think i understand what the reason of your error. First you click auto AUTO INCREMENT field then select it as a primary key.
The Right way is First You have to select it as a primary key then you have to click auto AUTO INCREMENT field.
Very easy. Thanks
It turns out setting these configuration properties is pretty straight forward, but the official documentation is more general so it might be hard to find when searching specifically for connection pool configuration information.
To set the maximum pool size for tomcat-jdbc, set this property in your .properties or .yml file:
spring.datasource.maxActive=5
You can also use the following if you prefer:
spring.datasource.max-active=5
You can set any connection pool property you want this way. Here is a complete list of properties supported by tomcat-jdbc
.
To understand how this works more generally you need to dig into the Spring-Boot code a bit.
Spring-Boot constructs the DataSource like this (see here, line 102):
@ConfigurationProperties(prefix = DataSourceAutoConfiguration.CONFIGURATION_PREFIX)
@Bean
public DataSource dataSource() {
DataSourceBuilder factory = DataSourceBuilder
.create(this.properties.getClassLoader())
.driverClassName(this.properties.getDriverClassName())
.url(this.properties.getUrl())
.username(this.properties.getUsername())
.password(this.properties.getPassword());
return factory.build();
}
The DataSourceBuilder is responsible for figuring out which pooling library to use, by checking for each of a series of know classes on the classpath. It then constructs the DataSource and returns it to the dataSource()
function.
At this point, magic kicks in using @ConfigurationProperties
. This annotation tells Spring to look for properties with prefix CONFIGURATION_PREFIX
(which is spring.datasource
). For each property that starts with that prefix, Spring will try to call the setter on the DataSource with that property.
The Tomcat DataSource is an extension of DataSourceProxy, which has the method setMaxActive()
.
And that's how your spring.datasource.maxActive=5
gets applied correctly!
I haven't tried, but if you are using one of the other Spring-Boot supported connection pools (currently HikariCP or Commons DBCP) you should be able to set the properties the same way, but you'll need to look at the project documentation to know what is available.
Actually, for UTC I used Z
instead of X
, e.g.
${__time(yyyy-MM-dd'T'hh:mm:ssZ)}
which gave me:
2017-09-14T09:24:54-0400
This is works. Kind of.
public static Object[] toArray(List<?> a) {
Object[] arr = new Object[a.size()];
for (int i = 0; i < a.size(); i++)
arr[i] = a.get(i);
return arr;
}
Then the main method.
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("hello");
add("world");
}};
Object[] arr = toArray(list);
System.out.println(arr[0]);
}
You should use the EndXXX of your async method to return the value. EndXXX should wait until there is a result using the IAsyncResult's WaitHandle and than return with the value.
If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.
Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.
Consider a program ArgsTest.java:
package test;
import java.io.IOException;
public class ArgsTest {
public static void main(String[] args) throws IOException {
System.out.println("Program Arguments:");
for (String arg : args) {
System.out.println("\t" + arg);
}
System.out.println("System Properties from VM Arguments");
String sysProp1 = "sysProp1";
System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
String sysProp2 = "sysProp2";
System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));
}
}
If given input as,
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
in the commandline, in project bin folder would give the following result:
Program Arguments: pro1 pro2 pro3 System Properties from VM Arguments Name:sysProp1, Value:sp1 Name:sysProp2, Value:sp2
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
Normally I do like this
git push https://$(git_token)@github.com/user_name/repo_name.git
The git_token is reading from variable config in azure devops.
You can read my full blog here
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = new Date();_x000D_
var timeDiff = endTime - startTime; //in ms_x000D_
// strip the ms_x000D_
timeDiff /= 1000;_x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = performance.now();_x000D_
var timeDiff = endTime - startTime; //in ms _x000D_
// strip the ms _x000D_
timeDiff /= 1000; _x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
In Eclipse Photon you may need to add JUnit 4 or 5 to the build path. Right click @Test and select 'Add JUnit 4 to build path'.
Unfortunately it's not trivial to do portably. You probably need a bit of expr magic.
for file in *.html; do echo mv -- "$file" "$(expr "$file" : '\(.*\)\.html').txt"; done
Remove the echo once you're happy it does what you want.
Edit: basename
is probably a little more readable for this particular case, although expr
is more flexible in general.
To get the list of multiple records use following command
select field1,field2,field3, count(*)
from table_name
group by field1,field2,field3
having count(*) > 1
In terms of speed: #1 and #4, but not by much in most instances.
You could write a benchmark to confirm, but I suspect you'll find #1 and #4 to be slightly faster because the iteration work is done in C instead of Perl, and no needless copying of the array elements occurs. ($_
is aliased to the element in #1, but #2 and #3 actually copy the scalars from the array.)
#5 might be similar.
In terms memory usage: They're all the same except for #5.
for (@a)
is special-cased to avoid flattening the array. The loop iterates over the indexes of the array.
In terms of readability: #1.
In terms of flexibility: #1/#4 and #5.
#2 does not support elements that are false. #2 and #3 are destructive.
if (!json[0]) alert("JSON empty");
i got this error when using this settings on web.config
System.ServiceModel.ServiceActivationException
i set settings like this:
<service name="idst.Controllers.wcf.Service_Talks">
<endpoint address="" behaviorConfiguration="idst.Controllers.wcf.Service_TalksAspNetAjaxBehavior"
binding="webHttpBinding" contract="idst.Controllers.wcf.Service_Talks" />
</service>
<service name="idst.Controllers.wcf.Service_Project">
<endpoint address="" behaviorConfiguration="idst.Controllers.wcf.Service_ProjectAspNetAjaxBehavior"
binding="basicHttpBinding" bindingConfiguration="" bindingName="largBasicHttp"
contract="idst.Controllers.wcf.Service_Project" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="largBasicHttp" allowCookies="true"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000">
<readerQuotas maxDepth="32"
maxArrayLength="200000000"
maxStringContentLength="200000000"/>
</binding>
</basicHttpBinding>
Workaround:
t = time()
t2 = time(t.hour+1, t.minute, t.second, t.microsecond)
You can also omit the microseconds, if you don't need that much precision.
1) To redirect to the login page / from the login page, don't use the Redirect() methods. Use FormsAuthentication.RedirectToLoginPage()
and FormsAuthentication.RedirectFromLoginPage()
!
2) You should just use RedirectToAction("action", "controller") in regular scenarios..
You want to redirect in side the Initialize method? Why? I don't see why would you ever want to do this, and in most cases you should review your approach imo.. If you want to do this for authentication this is DEFINITELY the wrong way (with very little chances foe an exception)
Use the [Authorize]
attribute on your controller or method instead :)
UPD: if you have some security checks in the Initialise method, and the user doesn't have access to this method, you can do a couple of things: a)
Response.StatusCode = 403;
Response.End();
This will send the user back to the login page. If you want to send him to a custom location, you can do something like this (cautios: pseudocode)
Response.Redirect(Url.Action("action", "controller"));
No need to specify the full url. This should be enough. If you completely insist on the full url:
Response.Redirect(new Uri(Request.Url, Url.Action("action", "controller")).ToString());
Radu Simionescu's answer worked for me. Thank you. For those who are unable to see the ip address of their android device, go to
Settings > Wireless > Wi-Fi
and then long press the wifi which you are connected to. Then select Modify network config
check on Show Advance Options
and the scroll to IP address
section.
After installing adb
in your system, do run
killadd adb
and adb start-server
to refresh adb. Sometimes we could get issues like here
Maybe not what you were looking for, but perhaps nice for someone to know:
If you are using .net Web Api 2 you could just do the following:
if (!ModelState.IsValid)
return BadRequest(ModelState);
Depending on the model errors, you get this result:
{
Message: "The request is invalid."
ModelState: {
model.PropertyA: [
"The PropertyA field is required."
],
model.PropertyB: [
"The PropertyB field is required."
]
}
}
The EXTRA_ALLOW_MULTIPLE option is set on the intent through the Intent.putExtra() method:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Your code above should look like this:
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
Note: the EXTRA_ALLOW_MULTIPLE
option is only available in Android API 18 and higher.
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)
Try using ReadAsStringAsync() instead.
var foo = resp.Content.ReadAsStringAsync().Result;
The reason why it ReadAsAsync<string>()
doesn't work is because ReadAsAsync<>
will try to use one of the default MediaTypeFormatter
(i.e. JsonMediaTypeFormatter
, XmlMediaTypeFormatter
, ...) to read the content with content-type
of text/plain
. However, none of the default formatter can read the text/plain
(they can only read application/json
, application/xml
, etc).
By using ReadAsStringAsync()
, the content will be read as string regardless of the content-type.
Just clean every content under .m2-->repository folder.When you build project all dependencies load here.
In your case may be your project earlier was using old version of any dependency and now version is upgraded.So better clean .m2 folder and build your project with mvn clean install.
Now dependencies with latest version modules will be downloaded in this folder.
Replacing substrings should not be that hard.
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
Tests:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not changed: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
Output:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
Maybe you are trying to set it in Apache's php.ini
, but your CLI (Command Line Interface) php.ini
is not good.
Find your php.ini
file with the following command:
php -i | grep php.ini
And then search for date.timezone
and set it to "Europe/Amsterdam"
. all valid timezone will be found here http://php.net/manual/en/timezones.php
Another way (if the other does not work), search for the file AppKernel.php
, which should be under the folder app
of your Symfony project directory. Overwrite the __construct
function below in the class AppKernel
:
<?php
class AppKernel extends Kernel
{
// Other methods and variables
// Append this init function below
public function __construct($environment, $debug)
{
date_default_timezone_set( 'Europe/Paris' );
parent::__construct($environment, $debug);
}
}
If you don't want the text to wrap and you don't want the size of the column to get bigger then set a width and height on the column and set "overflow: hidden" in your stylesheet.
To do this on only one column you will want to add a class to that column on each row. Otherwise you can set it on all columns, that is up to you.
Html:
<table width="300px">
<tr>
<td>Column 1</td><td>Column 2</td>
</tr>
<tr>
<td class="column-1">this is the text in column one which wraps</td>
<td>this is the column two test</td>
</tr>
</table>
stylsheet:
.column-1
{
overflow: hidden;
width: 150px;
height: 1.2ex;
}
An ex unit is the relative font size for height, if you are using pixels to set the font size you may wish to use that instead.
XAMPP and WAMP are both web server applications for PHP and MYSQL with the apache server. When we consider IIS, it also a web-server like apache runs on windows only.
XWAMPP/WAMP - Windows,Apache,Mysql,PHP
IIS - Apache,SQL Server, ASP.NET
If you like to read more about XWAMPP vs WAMP
Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for you. It is written in Golang and is lightweight, modular, portable and extensible. We (the Kubernetes team) are working with a number of different technology companies (including Mesosphere who curate the Mesos open source project) to establish Kubernetes as the standard way to interact with computing clusters. The idea is to reproduce the patterns that we see people needing to build cluster applications based on our experience at Google. Some of these concepts include:
So with Kubernetes alone you will have something that is simple, easy to get up-and-running, portable and extensible that adds 'cluster' as a noun to the things that you manage in the lightest weight manner possible. Run an application on a cluster, and stop worrying about an individual machine. In this case, cluster is a flexible resource just like a VM. It is a logical computing unit. Turn it up, use it, resize it, turn it down quickly and easily.
With Mesos, there is a fair amount of overlap in terms of the basic vision, but the products are at quite different points in their lifecycle and have different sweet spots. Mesos is a distributed systems kernel that stitches together a lot of different machines into a logical computer. It was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application run well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps. It is somewhat more heavy weight than the Kubernetes project, but is getting easier and easier to manage thanks to the work of folks like Mesosphere.
Now what gets really interesting is that Mesos is currently being adapted to add a lot of the Kubernetes concepts and to support the Kubernetes API. So it will be a gateway to getting more capabilities for your Kubernetes app (high availability master, more advanced scheduling semantics, ability to scale to a very large number of nodes) if you need them, and is well suited to run production workloads (Kubernetes is still in an alpha state).
When asked, I tend to say:
Kubernetes is a great place to start if you are new to the clustering world; it is the quickest, easiest and lightest way to kick the tires and start experimenting with cluster oriented development. It offers a very high level of portability since it is being supported by a lot of different providers (Microsoft, IBM, Red Hat, CoreOs, MesoSphere, VMWare, etc).
If you have existing workloads (Hadoop, Spark, Kafka, etc), Mesos gives you a framework that let's you interleave those workloads with each other, and mix in a some of the new stuff including Kubernetes apps.
Mesos gives you an escape valve if you need capabilities that are not yet implemented by the community in the Kubernetes framework.
The KILL SESSION
command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.
Check the status to confirm:
SELECT sid, serial#, status, username FROM v$session;
You could also use IMMEDIATE clause:
ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;
The IMMEDIATE
clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.
Update If you want to kill all the sessions, you could just prepare a small script.
SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;
Spool the above to a .sql
file and execute it, or, copy paste the output and run it.
encoding this line fixed it for me.
m.update(line.encode('utf-8'))
UConverter can be used since PHP 5.5. UConverter is better the choice if you use intl extension and don't use mbstring.
function replace_invalid_byte_sequence($str)
{
return UConverter::transcode($str, 'UTF-8', 'UTF-8');
}
function replace_invalid_byte_sequence2($str)
{
return (new UConverter('UTF-8', 'UTF-8'))->convert($str);
}
htmlspecialchars can be used to remove invalid byte sequence since PHP 5.4. Htmlspecialchars is better than preg_match for handling large size of byte and the accuracy. A lot of the wrong implementation by using regular expression can be seen.
function replace_invalid_byte_sequence3($str)
{
return htmlspecialchars_decode(htmlspecialchars($str, ENT_SUBSTITUTE, 'UTF-8'));
}
I got the same error while working with mnist data set, looks like a problem with the dimensions of X_train. I added another dimension and it solved the purpose.
X_train, X_test, \ y_train, y_test = train_test_split(X_reshaped, y_labels, train_size = 0.8, random_state = 42)
X_train = X_train.reshape(-1,28, 28, 1)
X_test = X_test.reshape(-1,28, 28, 1)
JPA specification contains a very precise description of semantics of these operations, better than in javadoc:
The semantics of the persist operation, applied to an entity X are as follows:
If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.
If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the
cascade=PERSIST
orcascade=ALL
annotation element value or specified with the equivalent XML descriptor element.If X is a removed entity, it becomes managed.
If X is a detached object, the
EntityExistsException
may be thrown when the persist operation is invoked, or theEntityExistsException
or anotherPersistenceException
may be thrown at flush or commit time.For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value
cascade=PERSIST
orcascade=ALL
, the persist operation is applied to Y.
The semantics of the merge operation applied to an entity X are as follows:
If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.
If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.
If X is a removed entity instance, an
IllegalArgumentException
will be thrown by the merge operation (or the transaction commit will fail).If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value
cascade=MERGE
orcascade=ALL
annotation.For all entities Y referenced by relationships from X having the cascade element value
cascade=MERGE
orcascade=ALL
, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)If X is an entity merged to X', with a reference to another entity Y, where
cascade=MERGE
orcascade=ALL
is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.
For specific formats like yours ".drp ". You can directly pass that in accept=".drp" it will work for that.
But without " * "
<input name="Upload Saved Replay" type="file" accept=".drp" />_x000D_
<br/>
_x000D_
I think you're confused about types here. You'll only get that result if you're multiplying a string. Start the interpreter and try this:
>>> print "1" * 9
111111111
>>> print 1 * 9
9
>>> print int("1") * 9
9
So make sure the first operand is an integer (and not a string), and it will work.
In addition to what @berguiga-mohamed-amine stated, I just found that a wildcard requires leaving the module argument the empty string:
compile ("com.github.jsonld-java:jsonld-java:$jsonldJavaVersion") {
exclude group: 'org.apache.httpcomponents', module: ''
exclude group: 'org.slf4j', module: ''
}
I have the same problem on Android Studio. No need to restart the IDE, just close and reopen the project and that will resolve the problem. (Make sure the src are correclty input).
I'm not repeating what is instructed here to input the Key store, password, etc. Try
Build -> Generate Signed APK -> [ Input ] ---Next---> select BOTH
I don't know why, but at least it worked in my situation.
some aliases in ~/.oh-my-zsh/plugins/git/git.plugin.zsh
gke='\gitk --all $(git log -g --pretty=%h)'
glg='git log --stat'
glgg='git log --graph'
glgga='git log --graph --decorate --all'
glgm='git log --graph --max-count=10'
glgp='git log --stat -p'
glo='git log --oneline --decorate'
glog='git log --oneline --decorate --graph'
gloga='git log --oneline --decorate --graph --all'
glol='git log --graph --pretty='\''%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'\'' --abbrev-commit'
glola='git log --graph --pretty='\''%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'\'' --abbrev-commit --all'
$('#mainn').text(function (_,txt) {
return txt.slice(0, -1);
});
demo -->
http://jsfiddle.net/d72ML/8/
File -> Export -> Web -> WAR file
OR in Kepler follow as shown below :
From the HTTP core module docs:
Example from the documentation:
location = / {
# matches the query / only.
[ configuration A ]
}
location / {
# matches any query, since all queries begin with /, but regular
# expressions and any longer conventional blocks will be
# matched first.
[ configuration B ]
}
location /documents/ {
# matches any query beginning with /documents/ and continues searching,
# so regular expressions will be checked. This will be matched only if
# regular expressions don't find a match.
[ configuration C ]
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
# Configuration D.
[ configuration E ]
}
If it's still confusing, here's a longer explanation.
I suggest this one:
if [ "$a" = "$b" ]
Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the '=' sign.
Also, be careful of your script header. It's not the same thing whether you use
#!/bin/bash
or
#!/bin/sh
I had only 12 Mb for the SD Card in the AVD device.
Increasing it to 2 Gb solved the issue.
You shall pass a this
pointer to tell the function which object to work on because it relies on that as opposed to a static
member function.
Instead of installing a library inside Jupyter, I would recommend you use the 'Dark Reader' extension in Chrome (you can find 'Dark Reader' extension in other browsers, e.g. Firefox). You can play with it; filter the URL(s) you want to have dark theme, or even how define the Dark theme for yourself. Below are couple of examples:
I hope it helps.
The notation that is used in
a[::-1]
means that for a given string/list/tuple, you can slice the said object using the format
<object_name>[<start_index>, <stop_index>, <step>]
This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.
In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.
So,
a = '1234'
print a[::2]
would print
13
Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example
a = '1234'
print a[3:0:-1]
This would return
432
Note, that it doesn't return 4321 because, the stop index is not included.
Now in your case,
str(int(a[::-1]))
would just reverse a given integer, that is stored in a string, and then convert it back to a string
i.e "1234" -> "4321" -> 4321 -> "4321"
If what you are trying to do is just reverse the given string, then simply a[::-1] would work .
It depends on the tools you can use. I doubt there is a JavaScript too that could do it directly within the browser. It also depends if it's a one-off (always the same key) or whether you need to script it.
If you want to use something like OpenSSL on a unix command line, you can do something as follows. I'm assuming you public.key file contains something like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmBAjFv+29CaiQqYZIw4P
J0q5Qz2gS7kbGleS3ai8Xbhu5n8PLomldxbRz0RpdCuxqd1yvaicqpDKe/TT09sR
mL1h8Sx3Qa3EQmqI0TcEEqk27Ak0DTFxuVrq7c5hHB5fbJ4o7iEq5MYfdSl4pZax
UxdNv4jRElymdap8/iOo3SU1RsaK6y7kox1/tm2cfWZZhMlRFYJnpoXpyNYrp+Yo
CNKxmZJnMsS698kaFjDlyznLlihwMroY0mQvdD7dCeBoVlfPUGPAlamwWyqtIU+9
5xVkSp3kxcNcNb/mePSKQIPafQ1sAmBKPwycA/1I5nLzDVuQa95ZWMn0JkphtFIh
HQIDAQAB
-----END PUBLIC KEY-----
Then, the commands would be:
PUBKEY=`grep -v -- ----- public.key | tr -d '\n'`
Then, you can look into the ASN.1 structure:
echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i
This should give you something like this:
0:d=0 hl=4 l= 290 cons: SEQUENCE
4:d=1 hl=2 l= 13 cons: SEQUENCE
6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
17:d=2 hl=2 l= 0 prim: NULL
19:d=1 hl=4 l= 271 prim: BIT STRING
The modulus and public exponent are in the last BIT STRING, offset 19, so use -strparse
:
echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i -strparse 19
This will give you the modulus and the public exponent, in hexadecimal (the two INTEGERs):
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :98102316FFB6F426A242A619230E0F274AB9433DA04BB91B1A5792DDA8BC5DB86EE67F0F2E89A57716D1CF4469742BB1A9DD72BDA89CAA90CA7BF4D3D3DB1198BD61F12C7741ADC4426A88D1370412A936EC09340D3171B95AEAEDCE611C1E5F6C9E28EE212AE4C61F752978A596B153174DBF88D1125CA675AA7CFE23A8DD253546C68AEB2EE4A31D7FB66D9C7D665984C951158267A685E9C8D62BA7E62808D2B199926732C4BAF7C91A1630E5CB39CB96287032BA18D2642F743EDD09E0685657CF5063C095A9B05B2AAD214FBDE715644A9DE4C5C35C35BFE678F48A4083DA7D0D6C02604A3F0C9C03FD48E672F30D5B906BDE5958C9F4264A61B452211D
265:d=1 hl=2 l= 3 prim: INTEGER :010001
That's probably fine if it's always the same key, but this is probably not very convenient to put in a script.
Alternatively (and this might be easier to put into a script),
openssl rsa -pubin -inform PEM -text -noout < public.key
will return this:
Modulus (2048 bit):
00:98:10:23:16:ff:b6:f4:26:a2:42:a6:19:23:0e:
0f:27:4a:b9:43:3d:a0:4b:b9:1b:1a:57:92:dd:a8:
bc:5d:b8:6e:e6:7f:0f:2e:89:a5:77:16:d1:cf:44:
69:74:2b:b1:a9:dd:72:bd:a8:9c:aa:90:ca:7b:f4:
d3:d3:db:11:98:bd:61:f1:2c:77:41:ad:c4:42:6a:
88:d1:37:04:12:a9:36:ec:09:34:0d:31:71:b9:5a:
ea:ed:ce:61:1c:1e:5f:6c:9e:28:ee:21:2a:e4:c6:
1f:75:29:78:a5:96:b1:53:17:4d:bf:88:d1:12:5c:
a6:75:aa:7c:fe:23:a8:dd:25:35:46:c6:8a:eb:2e:
e4:a3:1d:7f:b6:6d:9c:7d:66:59:84:c9:51:15:82:
67:a6:85:e9:c8:d6:2b:a7:e6:28:08:d2:b1:99:92:
67:32:c4:ba:f7:c9:1a:16:30:e5:cb:39:cb:96:28:
70:32:ba:18:d2:64:2f:74:3e:dd:09:e0:68:56:57:
cf:50:63:c0:95:a9:b0:5b:2a:ad:21:4f:bd:e7:15:
64:4a:9d:e4:c5:c3:5c:35:bf:e6:78:f4:8a:40:83:
da:7d:0d:6c:02:60:4a:3f:0c:9c:03:fd:48:e6:72:
f3:0d:5b:90:6b:de:59:58:c9:f4:26:4a:61:b4:52:
21:1d
Exponent: 65537 (0x10001)
It depends on the input format. If it's an X.509 certificate in a keystore, use (RSAPublicKey)cert.getPublicKey()
: this object has two getters for the modulus and the exponent.
If it's in the format as above, you might want to use BouncyCastle and its PEMReader
to read it. I haven't tried the following code, but this would look more or less like this:
PEMReader pemReader = new PEMReader(new FileReader("file.pem"));
Object obj = pemReader.readObject();
pemReader.close();
if (obj instanceof X509Certificate) {
// Just in case your file contains in fact an X.509 certificate,
// useless otherwise.
obj = ((X509Certificate)obj).getPublicKey();
}
if (obj instanceof RSAPublicKey) {
// ... use the getters to get the BigIntegers.
}
(You can use BouncyCastle similarly in C# too.)
short a;
short b;
short c;
short d;
short e;
short f;
short g;
short h;
int i;
char j[256];
printf("BINARY CONVERTER\n\n\n");
//uses <stdlib.h>
while(1)
{
a=0;
b=0;
c=0;
d=0;
e=0;
f=0;
g=0;
h=0;
i=0;
gets(j);
i=atoi(j);
if(i>255){
printf("int i must not pass the value 255.\n");
i=0;
}
if(i>=128){
a=1;
i=i-128;}
if(i>=64){
b=1;
i=i-64;}
if(i>=32){
c=1;
i=i-32;}
if(i>=16){
d=1;
i=i-16;}
if(i>=8){
e=1;
i=i-8;}
if(i>=4){
f=1;
i=i-4;}
if(i>=2){
g=1;
i=i-2;}
if(i>=1){
h=1;
i=i-1;}
printf("\n%d%d%d%d%d%d%d%d\n\n",a,b,c,d,e,f,g,h);
}
No JavaScript needed if you use a button instead:
<form action="your_url" method="post">
<button type="submit" name="your_name" value="your_value" class="btn-link">Go</button>
</form>
You can style a button to look like a link, for example:
.btn-link {
border: none;
outline: none;
background: none;
cursor: pointer;
color: #0000EE;
padding: 0;
text-decoration: underline;
font-family: inherit;
font-size: inherit;
}
You must to upgrade the m2e connector. It's a known bug, but there is a solution:
Into Eclipse click "Help" > "Install new Software..."
Appears a window. In the "Install" window:
2a. Into the input box "Work with", enter next site location and press Enter https://download.eclipse.org/m2e-wtp/releases/1.4/
2b. Appears a lot of information into "Name" input Box. Select all the items
2c. Click "Next" Button.
Finish the installation and restart Eclipse.
S3_REGION="eu-central-1"
bucket="mybucket1"
name="objectname"
import boto3
from botocore.client import Config
client = boto3.client('s3',region_name=S3_REGION,config=Config(signature_version='s3v4'))
list = client.list_objects_v2(Bucket=bucket,Prefix=name)
for obj in list.get('Contents', []):
if obj['Key'] == name: return True
return False
Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.
Difference between OpenJDK and AdoptOpenJDK
The first provides source-code, the other provides builds of that source-code.
Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:
See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.
Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.
Here is a list of considerations and motivations to consider in choosing a vendor and implementation.
Some vendors offer you a choice of JIT technologies.
To understand more about this Java ecosystem, read Java Is Still Free
I know this question is old, but the solution to my application, was different to the already suggested answers. If anyone else like me still have this issue, and none of the above answers works, this might be the problem:
I used a Network Credentials object to parse a windows username+password to a third party SOAP webservice. I had set the username="domainname\username", password="password" and domain="domainname". Now this game me that strange Ntlm and not NTLM error. To solve the problems, make sure not to use the domain parameter on the NetworkCredentials object if the domain name is included in the username with the backslash. So either remove domain name from the username and parse in domain parameter, or leave out the domain parameter. This solved my issue.
Use sqlalchemy's text function to remove the interpretation of special characters:
Note the use of the function text("your_insert_statement")
below. What it does is communicate to sqlalchemy that all of the questionmarks and percent signs in the passed in string should be considered as literals.
import sqlalchemy
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import re
engine = sqlalchemy.create_engine("mysql+mysqlconnector://%s:%s@%s/%s"
% ("your_username", "your_password", "your_hostname_mysql_server:3306",
"your_database"),
pool_size=3, pool_recycle=3600)
conn = engine.connect()
myfile = open('access2.log', 'r')
lines = myfile.readlines()
penguins = []
for line in lines:
elements = re.split('\s+', line)
print "item: " + elements[0]
linedate = datetime.fromtimestamp(float(elements[0]))
mydate = linedate.strftime("%Y-%m-%d %H:%M:%S.%f")
penguins.append(text(
"insert into your_table (foobar) values('%%%????')"))
for penguin in penguins:
print penguin
conn.execute(penguin)
conn.close()
Another one:
str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
Anyway, for uniqueness, you will have to check that your number hasn't been already used.
You tell that you check for duplicates, but be cautious since when most numbers will be used, the number of "attempts" (and therefore the time taken) for getting a new number will increase, possibly resulting in very long delays & wasting CPU resources.
I would advise, if possible, to keep track of available IDs in an array, then randomly choose an ID among the available ones, by doing something like this (if ID list is kept in memory):
$arrayOfAvailableIDs = array_map(function($nb) {
return str_pad($nb, 6, '0', STR_PAD_LEFT);
}, range(0, 999999));
$nbAvailableIDs = count($arrayOfAvailableIDs);
// pick a random ID
$newID = array_splice($arrayOfAvailableIDs, mt_rand(0, $nbAvailableIDs-1), 1);
$nbAvailableIDs--;
You can do something similar even if the ID list is stored in a database.
You almost always use HashMap
, you should only use TreeMap
if you need your keys to be in a specific order.
Xcode supports text macros that can be invoked via the Insert Text Macro menu at the end of the Edit menu. They can also be invoked using Code Sense, Xcode's code completion technology.
For example, Typing the key sequence p i m control-period
will insert #import "file"
into your code, with file
as an editable token just like with code completion.
Encryption has not only cpu, but also some network overhead.
The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time
You can use Contains()
for that. It will feel a little backwards when you're really trying to produce an IN
clause, but this should do it:
var userProfiles = _dataContext.UserProfile
.Where(t => idList.Contains(t.Id));
I'm also assuming that each UserProfile
record is going to have an int
Id
field. If that's not the case you'll have to adjust accordingly.
use content
in iframe with JS:
document.getElementById('id_iframe').contentWindow.document.write('content');
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand(“spAddEmployee”, con);
//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Add the input parameters to the command object
cmd.Parameters.AddWithValue(“@Name”, txtEmployeeName.Text);
cmd.Parameters.AddWithValue(“@Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“@Salary”, txtSalary.Text);
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = “@EmployeeId”;
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
}
Font http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output
Probably a good idea to source whatever profile you edit to save having to use a fresh login.
either: source /etc/ or . /etc/
Where is whatever profile you edited.
I think flock
is probably the easiest (and most memorable) variant. I use it in a cron job to auto-encode dvds and cds
# try to run a command, but fail immediately if it's already running
flock -n /var/lock/myjob.lock my_bash_command
Use -w
for timeouts or leave out options to wait until the lock is released. Finally, the man page shows a nice example for multiple commands:
(
flock -n 9 || exit 1
# ... commands executed under lock ...
) 9>/var/lock/mylockfile
Not officially, no. It's just Objective-C though and the compiler's open source - you could probably get the headers and compile it and somehow get the binary on the device. Another option is compiling on the device. All these options will require jailbreaking though.
A Mac Mini is just $599...
I have done this way:
Get Compressed Bitmap from Singleton class:
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
imageView.setImageBitmap(bitmap);
ImageUtils.java:
public class ImageUtils {
public static ImageUtils mInstant;
public static ImageUtils getInstant(){
if(mInstant==null){
mInstant = new ImageUtils();
}
return mInstant;
}
public Bitmap getCompressedBitmap(String imagePath) {
float maxHeight = 1920.0f;
float maxWidth = 1080.0f;
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float imgRatio = (float) actualWidth / (float) actualHeight;
float maxRatio = maxWidth / maxHeight;
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
bmp = BitmapFactory.decodeFile(imagePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
ExifInterface exif = null;
try {
exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);
byte[] byteArray = out.toByteArray();
Bitmap updatedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
return updatedBitmap;
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
}
Dimensions are same after compressing Bitmap.
How did I checked ?
Bitmap beforeBitmap = BitmapFactory.decodeFile("Your_Image_Path_Here");
Log.i("Before Compress Dimension", beforeBitmap.getWidth()+"-"+beforeBitmap.getHeight());
Bitmap afterBitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
Log.i("After Compress Dimension", afterBitmap.getWidth() + "-" + afterBitmap.getHeight());
Output:
Before Compress : Dimension: 1080-1452
After Compress : Dimension: 1080-1452
Hope this will help you.
First Look at this example :
The C code for a simple C program is given below
struct Foo {
char a;
int b;
double c;
} foo1,foo2;
void foo_assign(void)
{
foo1 = foo2;
}
int main(/*char *argv[],int argc*/)
{
foo_assign();
return 0;
}
The Equivalent ASM Code for foo_assign() is
00401050 <_foo_assign>:
401050: 55 push %ebp
401051: 89 e5 mov %esp,%ebp
401053: a1 20 20 40 00 mov 0x402020,%eax
401058: a3 30 20 40 00 mov %eax,0x402030
40105d: a1 24 20 40 00 mov 0x402024,%eax
401062: a3 34 20 40 00 mov %eax,0x402034
401067: a1 28 20 40 00 mov 0x402028,%eax
40106c: a3 38 20 40 00 mov %eax,0x402038
401071: a1 2c 20 40 00 mov 0x40202c,%eax
401076: a3 3c 20 40 00 mov %eax,0x40203c
40107b: 5d pop %ebp
40107c: c3 ret
As you can see that a assignment is simply replaced by a "mov" instruction in assembly, the assignment operator simply means moving data from one memory location to another memory location. The assignment will only do it for immediate members of a structures and will fail to copy when you have Complex datatypes in a structure. Here COMPLEX means that you cant have array of pointers ,pointing to lists.
An array of characters within a structure will itself not work on most compilers, this is because assignment will simply try to copy without even looking at the datatype to be of complex type.
Use the string concatenation operator:
Dim str As String = New String("") & "some other string"
Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.
This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.
See "How to: Concatenate Multiple Strings" for more information on both methods.
As explained in other answers it converts the variable to a number. Specially useful when d
can be either a number or a string that evaluates to a number.
Example (using the addMonths
function in the question):
addMonths(34,1,true);
addMonths("34",1,true);
then the +d
will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d
is a number, a function or a string that can be converted to a number.
You do not need {{}}
in when conditions. What you are searching for is:
- fail: msg="unsupported version"
when: version not in acceptable_versions
If you are using the GET request to actually SEND data...
check: http://techhelplist.com/index.php/tech-tutorials/37-windows-troubles/60-vbscript-sending-get-request
The problem with MSXML2.XMLHTTP is that there are several versions of it, with different names depending on the windows os version and patches.
this explains it: http://support.microsoft.com/kb/269238
i have had more luck using vbscript to call
set ID = CreateObject("InternetExplorer.Application")
IE.visible = 0
IE.navigate "http://example.com/parser.php?key=" & value & "key2=" & value2
do while IE.Busy....
....and more stuff but just to let the request go thru.
Please, don't do it like that (passing GET var to be a part of a system call). Use ZipArchive instead.
So, your code should look like:
$zipArchive = new ZipArchive();
$result = $zipArchive->open($_GET["master"]);
if ($result === TRUE) {
$zipArchive ->extractTo("my_dir");
$zipArchive ->close();
// Do something else on success
} else {
// Do something on error
}
And to answer your question, your error is 'something $var something else' should be "something $var something else" (in double quotes).
Use jQuery $(document)
function...
$(document).ready(function(){
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
//d3.select('#chart svg')
//d3.select("body").append("svg")
//var svg = d3.select("#chart").append("svg:svg");
var svg = d3.select("#BarChart").append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var updateData = function(getData){
d3.selectAll('svg > g > *').remove();
d3.csv(getData, function(error, data) {
if (error) throw error;
var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });
data.forEach(function(d) {
d.ages = ageNames.map(function(name) { return {name: name, value: +d[name]}; });
});
x0.domain(data.map(function(d) { return d.State; }));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) { return d3.max(d.ages, function(d) { return d.value; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "state")
.attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
}
updateData('data1.csv');
});
If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):
For Xpath:
http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html
Use export if you want to upload (or give to somebody) a project. If you are working with a project, use checkout.
make_unique
is an upcoming C++14 feature and thus might not be available on your compiler, even if it is C++11 compliant.
You can however easily roll your own implementation:
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
(FYI, here is the final version of make_unique
that was voted into C++14. This includes additional functions to cover arrays, but the general idea is still the same.)
I stumbled on this post while trying to change the display format for dates in sql-developer. Just wanted to add to this what I found out:
But a lot of times, I just want to retain the DEFAULT_FORMAT while modifying the format only during a bunch of related queries. That's when I would change the format of the session with the following:
alter SESSION set NLS_DATE_FORMAT = 'my_required_date_format'
Eg:
alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS'
I gathered insights from a bunch of answers here and I present a comprehensive solution:
So, if you setup nginx with php5-fpm and log a message using error_log()
you can see it in /var/log/nginx/error.log
by default.
A problem can arise if you want to log a lot of data (say an array) using error_log(print_r($myArr, true));
. If an array is large enough, it seems that nginx
will truncate your log entry.
To get around this you can configure fpm
(php.net fpm config) to manage logs. Here are the steps to do so.
Open /etc/php5/fpm/pool.d/www.conf
:
$ sudo nano /etc/php5/fpm/pool.d/www.conf
Uncomment the following two lines by removing ;
at the beginning of the line: (error_log is defined here: php.net)
;php_admin_value[error_log] = /var/log/fpm-php.www.log
;php_admin_flag[log_errors] = on
Create /var/log/fpm-php.www.log
:
$ sudo touch /var/log/fpm-php.www.log;
Change ownership of /var/log/fpm-php.www.log
so that php5-fpm can edit it:
$ sudo chown vagrant /var/log/fpm-php.www.log
Note: vagrant
is the user that I need to give ownership to. You can see what user this should be for you by running $ ps aux | grep php.*www
and looking at first column.
Restart php5-fpm:
$ sudo service php5-fpm restart
Now your logs will be in /var/log/fpm-php.www.log
.
You used to be able to do this, but GitHub removed this feature at some point mid-2013. To achieve this locally, you can do:
git log -g --grep=STRING
(Use the -g
flag if you want to search other branches and dangling commits.)
-g, --walk-reflogs
Instead of walking the commit ancestry chain, walk reflog entries from
the most recent one to older ones.
regarding Kevin answer to write in a folder tmp
, it should be like this:
with open('./tmp/metadata.pdf', 'wb') as f:
f.write(response.content)
he forgot .
before the address and of-course your folder tmp
should have been created already
declare @temp as varchar
set @temp='Measure'
if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
If you want that for display purposes, use java.text.DecimalFormat
:
new DecimalFormat("#.##").format(dblVar);
If you need it for calculations, use java.lang.Math
:
Math.floor(value * 100) / 100;
In my opinion early return is fine if you are just returning void (or some useless return code you're never gonna check) and it might improve readability because you avoid nesting and at the same time you make explicit that your function is done.
If you are actually returning a returnValue - nesting is usually a better way to go cause you return your returnValue just in one place (at the end - duh), and it might make your code more maintainable in a whole lot of cases.
I use GET when I'm retrieving information from a URL and POST when I'm sending information to a URL.
B2 container position relative
Top position B2 + of remaining height
Height of B2 + height B1 or remaining height
Easiest and simplest way to change date format in php
In PHP any date can be converted into the required date format using different scenarios for example to change any date format into Day, Date Month Year
$newdate = date("D, d M Y", strtotime($date));
It will show date in the following very well format
Mon, 16 Nov 2020
And if you have time as well in your existing date format for example if you have datetime format of SQL 2020-11-11 22:00:00 you can convert this into the required date format using the following
$newdateformat = date("D, d M Y H:i:s", strtotime($oldateformat));
It will show date in following well looking format
Sun, 15 Nov 2020 16:26:00
You can also run a subset of tests, according to the documentation:
Running a Subset of the Tests
By default, a Google Test program runs all tests the user has defined. Sometimes, you want to run only a subset of the tests (e.g. for debugging or quickly verifying a change). If you set the GTEST_FILTER environment variable or the --gtest_filter flag to a filter string, Google Test will only run the tests whose full names (in the form of TestCaseName.TestName) match the filter.
The format of a filter is a ':'-separated list of wildcard patterns (called the positive patterns) optionally followed by a '-' and another ':'-separated pattern list (called the negative patterns). A test matches the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns.
A pattern may contain '*' (matches any string) or '?' (matches any single character). For convenience, the filter '*-NegativePatterns' can be also written as '-NegativePatterns'.
For example:
./foo_test Has no flag, and thus runs all its tests. ./foo_test --gtest_filter=* Also runs everything, due to the single match-everything * value. ./foo_test --gtest_filter=FooTest.* Runs everything in test case FooTest. ./foo_test --gtest_filter=*Null*:*Constructor* Runs any test whose full name contains either "Null" or "Constructor". ./foo_test --gtest_filter=-*DeathTest.* Runs all non-death tests. ./foo_test --gtest_filter=FooTest.*-FooTest.Bar Runs everything in test case FooTest except FooTest.Bar.
Not the prettiest solution, but it works.
Use the .date
method:
In [11]: t = pd.Timestamp('2013-12-25 00:00:00')
In [12]: t.date()
Out[12]: datetime.date(2013, 12, 25)
In [13]: t.date() == datetime.date(2013, 12, 25)
Out[13]: True
To compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:
In [21]: pd.Timestamp(datetime.date(2013, 12, 25))
Out[21]: Timestamp('2013-12-25 00:00:00')
In [22]: ts = pd.DatetimeIndex([t])
In [23]: ts == pd.Timestamp(datetime.date(2013, 12, 25))
Out[23]: array([ True], dtype=bool)
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson
function and add contentType: 'application/json;charset=UTF-8'
to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
I would end it with NULL
. Why? Because you can't do either of these:
array[index] == '\0'
array[index] == "\0"
The first one is comparing a char *
to a char
, which is not what you want. You would have to do this:
array[index][0] == '\0'
The second one doesn't even work. You're comparing a char *
to a char *
, yes, but this comparison is meaningless. It passes if the two pointers point to the same piece of memory. You can't use ==
to compare two strings, you have to use the strcmp()
function, because C has no built-in support for strings outside of a few (and I mean few) syntactic niceties. Whereas the following:
array[index] == NULL
Works just fine and conveys your point.
I solved changing
readable_json['firstName']
by
readable_json[0]['firstName']
As far as I know this:
div[class=yourclass] table { your style here; }
or in your case even this:
div.yourclass table { your style here; }
(but this will work for elements with yourclass
that might not be div
s) will affect only tables inside yourclass
. And, as Ken says, the > is not supported everywhere (and div[class=yourclass]
too, so use the point notation for classes).
I believe for this typical case, i.e. to run something with a fixed interval, Timer
is more appropriate. Here is a simple example:
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
// If you want to modify a view in your Activity
MyActivity.this.runOnUiThread(new Runnable()
public void run(){
tv.append("Hello World");
});
}
}, 1000, 1000); // initial delay 1 second, interval 1 second
Using Timer
has few advantages:
schedule
function argumentsmyTimer.cancel()
myTimer.cancel()
before scheduling a new one (if myTimer is not null)Use strtotime(..)
:
$timestamp = strtotime($mysqltime);
echo date("Y-m-d H:i:s", $timestamp);
Also check this out (to do it in MySQL way.)
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp
You can also use this script to figure out more info:
EXEC sp_server_info
The result will be something like that:
attribute_id | attribute_name | attribute_value
-------------|-----------------------|-----------------------------------
1 | DBMS_NAME | Microsoft SQL Server
2 | DBMS_VER | Microsoft SQL Server 2012 - 11.0.6020.0
10 | OWNER_TERM | owner
11 | TABLE_TERM | table
12 | MAX_OWNER_NAME_LENGTH | 128
13 | TABLE_LENGTH | 128
14 | MAX_QUAL_LENGTH | 128
15 | COLUMN_LENGTH | 128
16 | IDENTIFIER_CASE | MIXED
? ? ?
? ? ?
? ? ?
There's a public Web-accessible version of the Lambda-enabled Java 8 JavaDocs, linked from http://lambdafaq.org/lambda-resources. (This should obviously be a comment on Joachim Sauer's answer, but I can't get into my SO account with the reputation points I need to add a comment.) The lambdafaq site (I maintain it) answers this and a lot of other Java-lambda questions.
NB This answer was written before the Java 8 GA documentation became publicly available. I've left in place, though, because the Lambda FAQ might still be useful to people learning about features introduced in Java 8.
There are several different varieties of CRC-16. See wiki page.
Every of those will return different results from the same input.
So you must carefully select correct one for your program.
Just use ::after or ::before pseudo element to add the shadow. Make it 1px and position it on whatever side you want. Below is example of top.
footer {_x000D_
margin-top: 50px;_x000D_
color: #fff;_x000D_
background-color: #009eff;_x000D_
text-align: center;_x000D_
line-height: 90px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
footer::after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
width: 100%;_x000D_
height: 1px;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: -1;_x000D_
box-shadow: 0px 0px 10px 1px rgba(0, 0, 0, 0.75);_x000D_
}
_x000D_
<footer>top only box shadow</footer>
_x000D_
window.location.href = "/";
This worked for me. If you have multiple folders/directories, you can use this:
window.location.href = "/folder_name/";
Open Notepad
Type in the following:
javac *
java Main
SaveAs Main.bat or whatever name you wish to use for the batch file
Make sure that Main.java is in the same folder along with your batch file
Double Click on the batch file to run the Main.java file
Use EXPLAIN to see how your database executes the query on your data. There is a huge "it depends" in this answer...
PostgreSQL can rewrite a subquery to a join or a join to a subquery when it thinks one is faster than the other. It all depends on the data, indexes, correlation, amount of data, query, etc.
I shall refer to the same sample of data as posted in the question:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))
Running this code will give you
The original data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc
to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append
returns a view of the dataframe and does not modify its contents. Following is the code:
row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))
Following would be the new output:
The new data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
3 10.000000 20.000000 30.000000 40.000000
You would probably would have to set the child div to have position: absolute
.
Update your child style to
#parentDiv .childDiv
{
height:100px;
width:30px;
background-color:#999;
position:absolute;
top:207px;
}
From http://docs.python.org/library/csv.html#csv.writer:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with
statement to close the file when you're done writing to it.
Tested example below:
from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
output.writerow(dict((fn,fn) for fn in headers))
output.writerows(rows)
I also face the similar Issue. Nothing programmer has to do to resolve this error. I informed to my oracle DBA team. They kill the session and worked like a charm.
A possible solution:
dir|find "bytes free"
a more "advanced solution", for Windows Xp and beyond:
wmic /node:"%COMPUTERNAME%" LogicalDisk Where DriveType="3" Get DeviceID,FreeSpace|find /I "c:"
The Windows Management Instrumentation Command-line (WMIC) tool (Wmic.exe) can gather vast amounts of information about about a Windows Server 2003 as well as Windows XP or Vista. The tool accesses the underlying hardware by using Windows Management Instrumentation (WMI). Not for Windows 2000.
As noted by Alexander Stohr in the comments:
dir
' will still do the job),dir
' is locale dependent.If you would like to open link in a new tab, you can:
$("a#thing_to_click").on('click',function(){
window.open('https://yoururl.com', '_blank');
});
In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:
const tampax = require('tampax');
const yamlString = `
dude:
name: Arthur
weapon:
favorite: Excalibur
useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;
const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);
// output : "Arthur use Excalibur. The goal is to kill Mordred."
Editor's Note: poster is also the author of this package.
What about overriding the method with
void f(int value)
{
f((byte)value);
}
this will allow for f(0)
WELCOME TO 2020 *Drools in ES6*
Theres some pretty old answers in here - take advantage of destructuring. In my opinion this is without a doubt the nicest (very readable) way to iterate an object.
const myObject = {
nick: 'cage',
phil: 'murray',
};
Object.entries(myObject).forEach(([k,v]) => {
console.log("The key: ",k)
console.log("The value: ",v)
})
_x000D_
Edit:
As mentioned by Lazerbeak, map
allows you to cycle an object and use the key and value to make an array.
const myObject = {
nick: 'cage',
phil: 'murray',
};
const myArray = Object.entries(myObject).map(([k, v]) => {
return `The key '${k}' has a value of '${v}'`;
});
console.log(myArray);
_x000D_
An improved version for recursive approach suggested by @schirrmacher to print key[value] for the entire object:
var jDepthLvl = 0;
function visit(object, objectAccessor=null) {
jDepthLvl++;
if (isIterable(object)) {
if(objectAccessor === null) {
console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- START ? ?", "background:yellow");
} else
console.log("%c"+spacesDepth(jDepthLvl)+objectAccessor+"%c:","color:purple;font-weight:bold", "color:black");
forEachIn(object, function (accessor, child) {
visit(child, accessor);
});
} else {
var value = object;
console.log("%c"
+ spacesDepth(jDepthLvl)
+ objectAccessor + "[%c" + value + "%c] "
,"color:blue","color:red","color:blue");
}
if(objectAccessor === null) {
console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- END ? ?", "background:yellow");
}
jDepthLvl--;
}
function spacesDepth(jDepthLvl) {
let jSpc="";
for (let jIter=0; jIter<jDepthLvl-1; jIter++) {
jSpc+="\u0020\u0020"
}
return jSpc;
}
function forEachIn(iterable, functionRef) {
for (var accessor in iterable) {
functionRef(accessor, iterable[accessor]);
}
}
function isIterable(element) {
return isArray(element) || isObject(element);
}
function isArray(element) {
return element.constructor == Array;
}
function isObject(element) {
return element.constructor == Object;
}
visit($OBJECT_OR_ARRAY$);
I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.
As @Maloric mentioned in his answer to this question:
var jo = JObject.Parse(myJsonString);
To use JObject, you need the following in your class file
using Newtonsoft.Json.Linq;
Internet Explorer 8 has developer tools which is similar to Firebug for Firefox. Opera has Opera DragonFly, and Google Chrome also has something called Developer Tools (Shift+Ctrl+J).
Here is more a more detailed answer to debug JavaScript in IE6-8: Using the IE8 'Developer Tools' to debug earlier IE versions
If you have standart output redirect to "nohup.out" just see who use this file
lsof | grep nohup.out
For MVC developers,
Without eval:
Your original string was not an actual string.
jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"
The easiest way to to wrap it all with a single quote.
jsonObj = '"{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"'
Then you can combine two steps to parse it to JSON:
$.parseJSON(jsonObj.slice(1,-1))
Why use a complicated solution if a simple one works too?
.child {
white-space: normal;
}
The new git-switch
command (starting in GIT 2.23) also has a flag --discard-changes
which should help you. git pull
might be necessary afterwards.
Warning: it's still considered to be experimental.
If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:
offset = 5
DF = DF.append([np.nan for x in range(offset)])
DF = DF.shift(periods=offset)
DF = DF.reset_index() #Only works if sequential index
Use window.confirm()
instead of window.alert()
.
HTML:
<input type="submit" onclick="return clicked();" value="Button" />
JavaScript:
function clicked() {
return confirm('clicked');
}
Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.
What most people seem to miss is that those same URL properties are also available to anchor elements:
// To process anchors on click
jQuery('a').click(function () {
if (this.hash) {
// Clicked anchor has a hash
} else {
// Clicked anchor does not have a hash
}
});
// To process anchors without waiting for an event
jQuery('a').each(function () {
if (this.hash) {
// Current anchor has a hash
} else {
// Current anchor does not have a hash
}
});
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
I think it is possible for the server to return content in response to a PUT. If you are using a response envelop format that allows for sideloaded data (such as the format consumed by ember-data), then you can also include other objects that may have been modified via database triggers, etc. (Sideloaded data is explicitly to reduce # of requests, and this seems like a fine place to optimize.)
If I just accept the PUT and have nothing to report back, I use status code 204 with no body. If I have something to report, I use status code 200, and include a body.
set "CMD=C:\Program Files (x86)\PDFtk\bin\pdftk"
echo cmd /K ""%CMD%" %D% output trimmed.pdf"
start cmd /K ""%CMD%" %D% output trimmed.pdf"
this worked for me in a batch file
No there isn't. You can specify a background image but that's not the same thing.
Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.
http://www.enterprisedb.com/products-services-training/products/postgres-enterprise-manager
Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.
When we use the round() function, it will not give correct values.
you can check it using, round (2.735) and round(2.725)
please use
import math
num = input('Enter a number')
print(math.ceil(num*100)/100)
You can imitate open source Dockerfile, for example:
Node: node12-github
RUN groupadd --gid 1000 node \
&& useradd --uid 1000 --gid node --shell /bin/bash --create-home node
superset: superset-github
RUN useradd --user-group --create-home --no-log-init --shell /bin/bash
superset
I think it's a good way to follow open source.
From FormData documention:
XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the
XMLHttpRequest
send()
method.
With an XMLHttpRequest
you can set the custom headers and then do the POST
.
element.is('.class1, .class2')
works, but it's 35% slower than
element.hasClass('class1') || element.hasClass('class2')
If you doubt what i say, you can verify on jsperf.com.
Hope this help someone.
You can't access java objects from JavaScript because there are no objects on client side. It only receives plain HTML page (hidden fields can help but it's not very good approach).
I suggest you to use ajax and @ResponseBody
.
Using CentOS7, logs are available using the command journalctl -u docker
. Answering distinctly, because @sabin's answer might be accurate for older versions of CentOS but was not true for me.
systemd has its own logging system called the journal. The logs for the docker daemon can be viewed using journalctl -u docker
You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.
A previous reply to this question has given a great explanation of what the various types are.
You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.
http://www.softwareverify.com/cpp/memory/index.html
Disclaimer: I designed Memory Validator.
Another interesting variant question can be:
How would you make "12345"
as "12 23 34 45"
without using another string?
Will following do?
for(int i=0; i < a.size()-1; ++i)
{
//b = a.substr(i, 2);
c = atoi((a.substr(i, 2)).c_str());
cout << c << " ";
}
(null == undefined) // true
(null === undefined) // false
Because === checks for both the type and value. Type of both are different but value is the same.
You can use ROLLUP
select nvl(name, 'SUM'), count(*)
from table
group by rollup(name)
If an object's creation/existence dependents on another object which can't be tailored, its tight coupling. And, if the dependency can be tailored, its loose coupling. Consider an example in Java:
class Car {
private Engine engine = new Engine( "X_COMPANY" ); // this car is being created with "X_COMPANY" engine
// Other parts
public Car() {
// implemenation
}
}
The client of Car
class can create one with ONLY "X_COMPANY" engine.
Consider breaking this coupling with ability to change that:
class Car {
private Engine engine;
// Other members
public Car( Engine engine ) { // this car can be created with any Engine type
this.engine = engine;
}
}
Now, a Car
is not dependent on an engine of "X_COMPANY" as it can be created with types.
A Java specific note: using Java interfaces just for de-coupling sake is not a proper desing approach. In Java, an interface has a purpose - to act as a contract which intrisically provides de-coupling behavior/advantage.
Bill Rosmus's comment in accepted answer has a good explanation.
What worked for me :
$where = '';
/* $this->db->like('ust.title',$query_data['search'])
->or_like('usr.f_name',$query_data['search'])
->or_like('usr.l_name',$query_data['search']);*/
$where .= "(ust.title like '%".$query_data['search']."%'";
$where .= " or usr.f_name like '%".$query_data['search']."%'";
$where .= "or usr.l_name like '%".$query_data['search']."%')";
$this->db->where($where);
$datas = $this->db->join(TBL_USERS.' AS usr','ust.user_id=usr.id')
->where_in('ust.id', $blog_list)
->select('ust.*,usr.f_name as f_name,usr.email as email,usr.avatar as avatar, usr.sex as sex')
->get_where(TBL_GURU_BLOG.' AS ust',[
'ust.deleted_at' => NULL,
'ust.status' => 1,
]);
I have to do this to create a query like this :
SELECT `ust`.*, `usr`.`f_name` as `f_name`, `usr`.`email` as `email`, `usr`.`avatar` as `avatar`, `usr`.`sex` as `sex` FROM `blog` AS `ust` JOIN `users` AS `usr` ON `ust`.`user_id`=`usr`.`id` WHERE (`ust`.`title` LIKE '%mer%' ESCAPE '!' OR `usr`.`f_name` LIKE '%lok%' ESCAPE '!' OR `usr`.`l_name` LIKE '%mer%' ESCAPE '!') AND `ust`.`id` IN('36', '37', '38') AND `ust`.`deleted_at` IS NULL AND `ust`.`status` = 1 ;