For those starting with an existing IDEA installation (IDEA 15 in my case) to which they're adding the Android SDK (and not starting formally speaking with Android Studio), ...
Download (just) the SDK to your filesystem (somewhere convenient to you; it doesn't matter where).
When creating your first project and you get to the Project SDK: bit (or adding the Android SDK ahead of time as you wish), navigate (New) to the root of what you exploded into the filesystem as suggested by some of the other answers here.
At that point you'll get a tiny dialog to confirm with:
Java SDK: 1.7 (e.g.)
Build target: Android 6.0 (e.g.)
You can click OK whereupon you'll see what you did as an option in the Project SDK: drop-down, e.g.:
Android API 23 Platform (java version "1.7.0_67")
In Android you can create shared buffer between C++ and Java (with directAlloc method) and manipulate it in both sides.
If you are using graph for navigation between fragments you can do this: From fragment A:
Bundle bundle = new Bundle();
bundle.putSerializable(KEY, yourObject);
Navigation.findNavController(view).navigate(R.id.fragment, bundle);
To fragment B:
Bundle bundle = getArguments();
object = (Object) bundle.getSerializable(KEY);
Of course your object must implement Serializable
I had this issue so I just took all my content, copy/pasted it into notepad, made a new php file, pasted back in, re-saved and overwrote, and.. that worked! It really was some relic of Microsoft Word editing...
The string that you pass to the constructor JSONObject
has to be escaped with quote()
:
public static java.lang.String quote(java.lang.String string)
Your code would now be:
JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);
You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.
Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.
To read up on this, check out this thread (from my very first Stackoverflow post no less)!
Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate
You can use a nullable DateTime for this.
Nullable<DateTime> myDateTime;
or the same thing written like this:
DateTime? myDateTime;
This is how you should be using mysql_fetch_assoc():
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
// Do stuff with $row
}
$result should be a resource. Even if the query returns no rows, $result is still a resource. The only time $result is a boolean value, is if there was an error when querying the database. In which case, you should find out what that error is by using mysql_error() and ensure that it can't happen. Then you don't have to hide from any errors.
You should always cover the base that errors may happen by doing:
if (!$result) {
die(mysql_error());
}
At least then you'll be more likely to actually fix the error, rather than leave the users with a glaring ugly error in their face.
Async/Await with axios
useEffect(() => {
const getData = async () => {
await axios.get('your_url')
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
});
}
getData()
}, [])
Use jQuery .siblings()
to select the matching sibling.
$(this).siblings('.bidbutton');
In regards to your code, see @Coulton. You'll need to use JavaScript.
Checkout either FitText (it does work in IE, they just ballsed their site somehow) or BigText.
FitText will allow you to scale some text in relation to the container it is in, while BigText is more about resizing different sections of text to be the same width within the container.
BigText will set your string to exactly the width of the container, whereas FitText is less pixel perfect. It starts by setting the font-size at 1/10th of the container element's width. It doesn't work very well with all fonts by default, but it has a setting which allows you to decrease or increase the 'power' of the re-size. It also allows you to set a min and max font-size. It will take a bit of fiddling to get working the first time, but does work great.
http://marabeas.io <- playing with it currently here. As far as I understand, BigText wouldn't work in my context at all.
For those of you using Angularjs, here's an Angular version of FitText I've made.
Here's a LESS mixin you can use to make @humanityANDpeace's solution a little more pretty:
@mqIterations: 19;
.fontResize(@i) when (@i > 0) {
@media all and (min-width: 100px * @i) { body { font-size:0.2em * @i; } }
.fontResize((@i - 1));
}
.fontResize(@mqIterations);
And an SCSS version thanks to @NIXin!
$mqIterations: 19;
@mixin fontResize($iterations) {
$i: 1;
@while $i <= $iterations {
@media all and (min-width: 100px * $i) { body { font-size:0.2em * $i; } }
$i: $i + 1;
}
}
@include fontResize($mqIterations);
A primitive int
cannot be null. If you need null, use Integer
instead.
The Host
Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host
header does not match any of the configured virtual hosts.
That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).
Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.
This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.
Although the webserver would know the hostname from Server Name Indication, the Host
header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host
header is still valid (and necessary).
Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host
header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD
RESOURCE
and PROTOCOL VERSION
and at least the Host
header, like this:
GET /someresource.html HTTP/1.1
Host: www.example.com
In the MDN Documentation on the "Host" header they actually phrase it like this:
A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.
As mentioned by Darrel Miller, the complete specs can be found in RFC7230.
If you have a string of binary data which is Base64 encoded, you should be able to do the following:
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
You should be able to write the resulting array to a file.
Both are of same concept but in atomic boolean it will provide atomicity to the operation in case the cpu switch happens in between.
={10,}
matches =
that is repeated 10 or more times.
If you are using uniform 1.5 then use this simple trick to add or remove attribute of check
Just add value="check" in your checkbox's input field.
Add this code in uniform.js
> function doCheckbox(elem){
> .click(function(){
if ( $(elem+':checked').val() == 'check' ) {
$(elem).attr('checked','checked');
}
else {
$(elem).removeAttr('checked');
}
if you not want to add value="check" in your input box because in some cases you add two checkboxes so use this
if ($(elem).is(':checked')) {
$(elem).attr('checked','checked');
}
else
{
$(elem).removeAttr('checked');
}
If you are using uniform 2.0 then use this simple trick to add or remove attribute of check
in this classUpdateChecked($tag, $el, options) {
function change
if ($el.prop) {
// jQuery 1.6+
$el.prop(c, isChecked);
}
To
if ($el.prop) {
// jQuery 1.6+
$el.prop(c, isChecked);
if (isChecked) {
$el.attr(c, c);
} else {
$el.removeAttr(c);
}
}
The HtmlDocument
class is a wrapper around the native IHtmlDocument2
COM interface.
You cannot easily create it from a string.
You should use the HTML Agility Pack.
I've found that really large numbers with really large fractional parts can cause problems when using modulo 1 to get the fraction.
import decimal
>>> d = decimal.Context(decimal.MAX_PREC).create_decimal(
... '143000000000000000000000000000000000000000000000000000000000000000000000000000.1231200000000000000002013210000000'
... )
...
>>> d % 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]
I instead grabbed the integral part and subtracted it first to help simplify the rest of it.
>>> d - d.to_integral()
Decimal('0.1231200000000000000002013210')
You may not have permission to dba_sequences. So you can always just do:
select * from user_sequences;
I know its a very old question, but just in case anyone lands here looking for the newest supported way to hide status bar on the go programmatically, you can do it as follows:
window.insetsController?.hide(WindowInsets.Type.statusBars())
and to show it again:
window.insetsController?.show(WindowInsets.Type.statusBars())
use DateTime.ParseExact
string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)
null
will use the current culture, which is somewhat dangerous. Try to supply a specific culture
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)
You can try using the Wshshell.Run method which gives you little control of the process you start with it. Or you could use the WshShell.Exec method which will give you control to terminate it, get a response, pass more parameters (other than commandline args), get status, and others
To use Run (Simple Method)
Dim ProgramPath, WshShell, ProgramArgs, WaitOnReturn,intWindowStyle
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
intWindowStyle=1
WaitOnReturn=True
WshShell.Run Chr (34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs,intWindowStyle, WaitOnReturn
ProgramPath is the full path to your script you want to run
ProgramArgs is the arguments you want to pass to the script. (NOTE: the arguments are separated by a space, if you want to use an argument that contains a space then you will have to enclose that argument in quotes [Safe way to do this is use CHR (34) Example ProgramArgs= chr (34) & "/Hello World" & chr (34)
])
IntWindowStyle is the integer that determines how the window will be displayed. More info on this and WaitOnReturn can be found here WshShell.Run Method
WaitOnReturn if true then the script will pause until the command has terminated, if false then the script will continue right after starting command.
NOTE: The Run method can return the exit code but you must set WaitOnReturn to True, and assign the 'WshShell.Run' to a variable. (EX: ExitCode=WshShell.Run (Command,intWindowStyle,True)
)
To Use EXEC (Advanced Method)
Dim ProgramPath, WshShell, ProgramArgs, Process, ScriptEngine
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
ScriptEngine="CScript.exe"
Set Process=WshShell.Exec (ScriptEngine & space (1) & Chr(34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs)
Do While Process.Status=0
'Currently Waiting on the program to finish execution.
WScript.Sleep 300
Loop
ProgramPath same as Run READ RUN'S DESCRIPTION
ProgramArgs DITTO
ScriptEngine The Engine you will be using for executing the script. since the exec method requires a win32 application, you need to specify this. Usually either "WScript.exe" or "CScript.exe". Note that in order to use stdin and stdout (we'll cover what these are a bit further down) you must choose "CScript.exe".
Process this is the Object that references to the program the script will start. It has several members and they are: ExitCode, ProcessID, Status, StdErr, StdIn, StdOut, Terminate.
More Details about the members of Process Object
Process.StdIn.WriteLine "Hello Other Worlds"
)Process.StdOut.ReadLine
. This is the stream that the called script will receive any information sent by the calling script's stdin. If you used the stdin's example then StdOut.Readline will return "Hello Other Worlds". If there is nothing to read then the script will hang while waiting for an output. meaning the script will appear to be Not RespondingRead
or ReadAll
instead of ReadLine
if you want. Use Read (X)
if you want to read X amount of characters. Or ReadAll
if you want the rest of the stream.For more information about WshShell.Exec go to Exec Method Windows Scripting Host
You can use the GetServices
method of ServiceController
class to get an array of all the services. Then, find your service by checking the ServiceName
property of each service. When you've found your service, call the Start
method to start it.
You should also check the Status
property to see what state it is already in before calling start (it may be running, paused, stopped, etc..).
Throwing another answer into the ring, this will give you those columns and more:
SELECT col.TABLE_CATALOG AS [Database]
, col.TABLE_SCHEMA AS Owner
, col.TABLE_NAME AS TableName
, col.COLUMN_NAME AS ColumnName
, col.ORDINAL_POSITION AS OrdinalPosition
, col.COLUMN_DEFAULT AS DefaultSetting
, col.DATA_TYPE AS DataType
, col.CHARACTER_MAXIMUM_LENGTH AS MaxLength
, col.DATETIME_PRECISION AS DatePrecision
, CAST(CASE col.IS_NULLABLE
WHEN 'NO' THEN 0
ELSE 1
END AS bit)AS IsNullable
, COLUMNPROPERTY(OBJECT_ID('[' + col.TABLE_SCHEMA + '].[' + col.TABLE_NAME + ']'), col.COLUMN_NAME, 'IsIdentity')AS IsIdentity
, COLUMNPROPERTY(OBJECT_ID('[' + col.TABLE_SCHEMA + '].[' + col.TABLE_NAME + ']'), col.COLUMN_NAME, 'IsComputed')AS IsComputed
, CAST(ISNULL(pk.is_primary_key, 0)AS bit)AS IsPrimaryKey
FROM INFORMATION_SCHEMA.COLUMNS AS col
LEFT JOIN(SELECT SCHEMA_NAME(o.schema_id)AS TABLE_SCHEMA
, o.name AS TABLE_NAME
, c.name AS COLUMN_NAME
, i.is_primary_key
FROM sys.indexes AS i JOIN sys.index_columns AS ic ON i.object_id = ic.object_id
AND i.index_id = ic.index_id
JOIN sys.objects AS o ON i.object_id = o.object_id
LEFT JOIN sys.columns AS c ON ic.object_id = c.object_id
AND c.column_id = ic.column_id
WHERE i.is_primary_key = 1)AS pk ON col.TABLE_NAME = pk.TABLE_NAME
AND col.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND col.COLUMN_NAME = pk.COLUMN_NAME
WHERE col.TABLE_NAME = 'YourTableName'
AND col.TABLE_SCHEMA = 'dbo'
ORDER BY col.TABLE_NAME, col.ORDINAL_POSITION;
If you're using RStudio, please consider never using the rm(list = ls())
approach!* Instead, you should build your workflow around frequently employing the Ctrl
+Shift
+F10
shortcut to restart your R session. This is the fastest way to both nuke the current set of user-defined variables AND to clear loaded packages, devices, etc. The reproducibility of your work will increase markedly by adopting this habit.
See this excellent thread on Rstudio community for (h/t @kierisi) for a more thorough discussion (the main gist is captured by what I've stated already).
I must admit my own first few years of R coding featured script after script starting with the rm
"trick" -- I'm writing this answer as advice to anyone else who may be starting out their R careers.
*of course there are legitimate uses for this -- much like attach
-- but beginning users will be much better served (IMO) crossing that bridge at a later date.
Try this:
System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config file
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
I don't like "[paths objectAtIndex:0]" because if Apple adds a new folder starting with "A", "B" oder "C", the "Documents"-folder isn't the first folder in the directory.
Better:
NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
When I create a root class, whose methods I defined using the arrow functions. When inheriting and overwriting the original function I noticed the same issue.
class C {
x = () => 1;
};
class CC extends C {
x = (foo) => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
this is solved by defining the method of the parent class without arrow functions
class C {
x() {
return 1;
};
};
class CC extends C {
x = foo => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
In the conceptual data model you worry only about the high level design - what tables should exist and the connections between them. In this phase you recognize entities in your model and the relationships between them.
The logical model comes after the conceptual modeling when you explicitly define what the columns in each table are. While writing the logical model, you might also take into consideration the actual database system you're designing for, but only if it affects the design (i.e., if there are no triggers you might want to remove some redundancy column etc.)
There is also physical model which elaborates on the logical model and assigns each column with it's type/length etc.
Here is a good table and picture that describes each of the three levels.
|----------------------|------------|---------|----------|
| Feature | Conceptual | Logical | Physical |
|----------------------|------------|---------|----------|
| Entity Names | X | X | |
| Entity Relationships | X | X | |
| Attributes | | X | |
| Primary Keys | | X | X |
| Foreign Keys | | X | X |
| Table Names | | | X |
| Column Names | | | X |
| Column Data Types | | | X |
|----------------------|------------|---------|----------|
In the definition of your Card
class, a declaration for a default construction appears:
class Card
{
// ...
Card(); // <== Declaration of default constructor!
// ...
};
But no corresponding definition is given. In fact, this function definition (from card.cpp
):
void Card() {
//nothing
}
Does not define a constructor, but rather a global function called Card
that returns void
. You probably meant to write this instead:
Card::Card() {
//nothing
}
Unless you do that, since the default constructor is declared but not defined, the linker will produce error about undefined references when a call to the default constructor is found.
The same applies to your constructor accepting two arguments. This:
void Card(Card::Rank rank, Card::Suit suit) {
cardRank = rank;
cardSuit = suit;
}
Should be rewritten into this:
Card::Card(Card::Rank rank, Card::Suit suit) {
cardRank = rank;
cardSuit = suit;
}
And the same also applies for other member functions: it seems you did not add the Card::
qualifier before the member function names in their definitions. Without it, those functions are global functions rather than definitions of member functions.
Your destructor, on the other hand, is declared but never defined. Just provide a definition for it in card.cpp
:
Card::~Card() { }
I have just written a blog article that addresses exactly this, which you may find useful: http://seewah.blogspot.com/2009/10/circle-overlay-on-google-map.html
Basically, you need to create a GGroundOverlay with the correct GLatLngBounds. The tricky bit is in working out the southwest corner coordinate and the northeast corner coordinate of this imaginery square (the GLatLngBounds) bounding this circle, based on the desired radius. The math is quite complicated, but you can just refer to getDestLatLng function in the blog. The rest should be pretty straightforward.
Add this extension somewhere:
extension String {
mutating func addString(str: String) {
self = self + str
}
}
Then you can call it like:
var str1 = "hi"
var str2 = " my name is"
str1.addString(str2)
println(str1) //hi my name is
A lot of good Swift extensions like this are in my repo here, check them out: https://github.com/goktugyil/EZSwiftExtensions
I don't know if this is new in sklearn
or pandas
, but I'm able to pass the data frame directly to sklearn
without converting the data frame to a numpy array or any other data types.
from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit(df[['B', 'C']], df['A'])
>>> reg.coef_
array([ 4.01182386e-01, 3.51587361e-04])
Your regex pattern needs to be in delimiters:
$numpattern="/^([0-9]+)$/";
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
From a comment:
I want to sort each set.
That's easy. For any set s
(or anything else iterable), sorted(s)
returns a list of the elements of s
in sorted order:
>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
Note that sorted
is giving you a list
, not a set
. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2}
and {2, 1}
are the same set.
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).
The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key
function:
>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
For more information, see the Sorting HOWTO in the official docs.
* See the comments for exceptions.
This question is ancient but..
Right after the opening body tag..
<!--[if gte IE 8]>
<div id="IE8Body">
<![endif]-->
Right before the closing body tag..
<!--[if gte IE 8]>
</div>
<![endif]-->
CSS..
#IE8Body #nav li ul {}
You could do this for all IE browsers using conditional statements, OR target ALL browsers by encapsulating all content in a div with browser name + version server-side
I also had the same issue when I tried to install a Windows service, in my case I managed to resolved the issue by removing blank spaces in the folder path to the service .exe, below is the command worked for me in a command prompt
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Press ENTER to change working directory
InstallUtil.exe C:\MyService\Release\ReminderService.exe
Press ENTER
I run a very simple bash script which takes all of 10 seconds to do the job and sends me a mail when done.
#!/bin/bash
sudo service nginx stop
sudo rm -rf /var/cache/nginx/*
sudo service nginx start | mail -s "Nginx Purged" [email protected]
exit 0
I was able to set up github actions to automatically commit the results of a node build command (yarn build
in my case but it should work with npm too) to the gh-pages
branch whenever a new commit is pushed to master.
While not completely ideal as i'd like to avoid committing the built files, it seems like this is currently the only way to publish to github pages.
I based my workflow off of this guide for a different react library, and had to make the following changes to get it to work for me:
yarn export
because that command does not exist and it doesn't seem to add anything helpful (you may also want to change the build line above it to suit your needs)env
directive to the yarn build
step so that I can include the SHA hash of the commit that generated the build inside my app, but this is optionalHere is my full github action:
name: github pages
on:
push:
branches:
- master
jobs:
deploy:
runs-on: ubuntu-18.04
steps:
- uses: actions/checkout@v2
- name: Setup Node
uses: actions/setup-node@v2-beta
with:
node-version: '12'
- name: Get yarn cache
id: yarn-cache
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Cache dependencies
uses: actions/cache@v2
with:
path: ${{ steps.yarn-cache.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- run: yarn install --frozen-lockfile
- run: yarn build
env:
REACT_APP_GIT_SHA: ${{ github.SHA }}
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build
The docs for next.js also provides instructions for setting up with Vercel which appears to be a hosting service for node.js apps similar to github pages. I have not tried this though and so cannot speak to how well it works.
This might be a little off the question, but for those interested in the randomness of the generated string, my answer would be:
import os
import string
def _pwd_gen(size=16):
chars = string.letters
chars_len = len(chars)
return str().join(chars[int(ord(c) / 256. * chars_len)] for c in os.urandom(size))
There are 2 main reasons for __init__.py
For convenience: the other users will not need to know your functions' exact location in your package hierarchy.
your_package/
__init__.py
file1.py
file2.py
...
fileN.py
# in __init__.py
from file1 import *
from file2 import *
...
from fileN import *
# in file1.py
def add():
pass
then others can call add() by
from your_package import add
without knowing file1, like
from your_package.file1 import add
If you want something to be initialized; for example, logging (which should be put in the top level):
import logging.config
logging.config.dictConfig(Your_logging_config)
to allow periods and any other character just add them like so:
change: '#[^a-zA-Z ]#
'
to:'#[^a-zA-Z .()!]#
'
This following:
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
Is the same as:
class C(object):
def __init__(self):
self._x = None
def _x_get(self):
return self._x
def _x_set(self, value):
self._x = value
def _x_del(self):
del self._x
x = property(_x_get, _x_set, _x_del,
"I'm the 'x' property.")
Is the same as:
class C(object):
def __init__(self):
self._x = None
def _x_get(self):
return self._x
def _x_set(self, value):
self._x = value
def _x_del(self):
del self._x
x = property(_x_get, doc="I'm the 'x' property.")
x = x.setter(_x_set)
x = x.deleter(_x_del)
Is the same as:
class C(object):
def __init__(self):
self._x = None
def _x_get(self):
return self._x
x = property(_x_get, doc="I'm the 'x' property.")
def _x_set(self, value):
self._x = value
x = x.setter(_x_set)
def _x_del(self):
del self._x
x = x.deleter(_x_del)
Which is the same as :
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
The solution posted here does not work for me. Therefore, I am posting this answer to help someone facing similar issue.
OS: Ubuntu 18
PostgreSQL: 9.5 (Hosted on Ubuntu)
Docker: Server Application (which connects to PostgreSQL)
I am using docker-compose.yml to build application.
STEP 1: Please add host.docker.internal:<docker0 IP>
version: '3'
services:
bank-server:
...
depends_on:
....
restart: on-failure
ports:
- 9090:9090
extra_hosts:
- "host.docker.internal:172.17.0.1"
To find IP of docker i.e. 172.17.0.1 (in my case)
you can use:
$> ifconfig docker0
docker0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 172.17.0.1 netmask 255.255.0.0 broadcast 172.17.255.255
OR
$> ip a
1: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
STEP 2: In postgresql.conf, change listen_addresses to listen_addresses = '*'
STEP 3: In pg_hba.conf, add this line
host all all 0.0.0.0/0 md5
STEP 4: Now restart postgresql service using, sudo service postgresql restart
STEP 5: Please use host.docker.internal
hostname to connect database from Server Application.
Ex: jdbc:postgresql://host.docker.internal:5432/bankDB
Enjoy!!
NullPointerException
in some cases!
Without criteria.setProjection(Projections.distinct(Projections.property("id")))
all query goes well!
This solution is bad!
Another way is use SQLQuery. In my case following code works fine:
List result = getSession().createSQLQuery(
"SELECT distinct u.id as usrId, b.currentBillingAccountType as oldUser_type,"
+ " r.accountTypeWhenRegister as newUser_type, count(r.accountTypeWhenRegister) as numOfRegUsers"
+ " FROM recommendations r, users u, billing_accounts b WHERE "
+ " r.user_fk = u.id and"
+ " b.user_fk = u.id and"
+ " r.activated = true and"
+ " r.audit_CD > :monthAgo and"
+ " r.bonusExceeded is null and"
+ " group by u.id, r.accountTypeWhenRegister")
.addScalar("usrId", Hibernate.LONG)
.addScalar("oldUser_type", Hibernate.INTEGER)
.addScalar("newUser_type", Hibernate.INTEGER)
.addScalar("numOfRegUsers", Hibernate.BIG_INTEGER)
.setParameter("monthAgo", monthAgo)
.setMaxResults(20)
.list();
Distinction is done in data base! In opposite to:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
where distinction is done in memory, after load entities!
You can drop the database
and then recreate it with the below:-
mysql> drop database [database name];
mysql> create database [database name];
You can use mx.DateTime module
import mx.DateTime as mt
t1 = mt.now()
t2 = mt.now()
print int((t2-t1).seconds)
You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.
A simple example:
import difflib
cases=[('afrykanerskojezyczny', 'afrykanerskojezycznym'),
('afrykanerskojezyczni', 'nieafrykanerskojezyczni'),
('afrykanerskojezycznym', 'afrykanerskojezyczny'),
('nieafrykanerskojezyczni', 'afrykanerskojezyczni'),
('nieafrynerskojezyczni', 'afrykanerskojzyczni'),
('abcdefg','xac')]
for a,b in cases:
print('{} => {}'.format(a,b))
for i,s in enumerate(difflib.ndiff(a, b)):
if s[0]==' ': continue
elif s[0]=='-':
print(u'Delete "{}" from position {}'.format(s[-1],i))
elif s[0]=='+':
print(u'Add "{}" to position {}'.format(s[-1],i))
print()
prints:
afrykanerskojezyczny => afrykanerskojezycznym
Add "m" to position 20
afrykanerskojezyczni => nieafrykanerskojezyczni
Add "n" to position 0
Add "i" to position 1
Add "e" to position 2
afrykanerskojezycznym => afrykanerskojezyczny
Delete "m" from position 20
nieafrykanerskojezyczni => afrykanerskojezyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
nieafrynerskojezyczni => afrykanerskojzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
Add "k" to position 7
Add "a" to position 8
Delete "e" from position 16
abcdefg => xac
Add "x" to position 0
Delete "b" from position 2
Delete "d" from position 4
Delete "e" from position 5
Delete "f" from position 6
Delete "g" from position 7
For a precise answer to this question on "How to send data via intent from an Activity to Service", Is that you have to override the onStartCommand()
method which is where you receive the intent object:
When you create a Service
you should override the onStartCommand()
method so if you closely look at the signature below, this is where you receive the intent
object which is passed to it:
public int onStartCommand(Intent intent, int flags, int startId)
So from an activity you will create the intent object to start service and then you place your data inside the intent object for example you want to pass a UserID
from Activity
to Service
:
Intent serviceIntent = new Intent(YourService.class.getName())
serviceIntent.putExtra("UserID", "123456");
context.startService(serviceIntent);
When the service is started its onStartCommand()
method will be called so in this method you can retrieve the value (UserID) from the intent object for example
public int onStartCommand (Intent intent, int flags, int startId) {
String userID = intent.getStringExtra("UserID");
return START_STICKY;
}
Note: the above answer specifies to get an Intent with getIntent()
method which is not correct in context of a service
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
xxd
does both binary and hexadecimal.
bin:
xxd -b file
hex:
xxd file
And once you get things working again you should look into using something like subversion or mercurial for backup and revision control. Remember that he electrons don't always go where they are supposed to, backup early and often!
This tutorial shows a great way to do pagination. Efficient Pagination Using MySQL
In short, avoid to use OFFSET or large LIMIT
Include jQuery migration plugin along with your jQuery library.
In R the equivalent function is seq
and you can use it with the option by
:
seq(from = 5, to = 100, by = 5)
# [1] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
In addition to by
you can also have other options such as length.out
and along.with
.
length.out: If you want to get a total of 10 numbers between 0 and 1, for example:
seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1
along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).
seq(along.with=c(10,20,30))
# [1] 1 2 3
Although, instead of using the along.with
option, it is recommended to use seq_along
in this case. From the documentation for ?seq
seq
is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to useseq_along
in that case.
seq_along: Instead of seq(along.with(.))
seq_along(c(10,20,30))
# [1] 1 2 3
Hope this helps.
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
$(this).click(function(e) {
// does something
});
In reference to the above code
$(this)
is the element which as some variable.
click
is the event that needs to be performed.
the parameter e
is automatically passed from js to your function which holds the value of $(this)
value and can be used further in your code to do some operation.
You need to restart the process if app.get
not working. Press ctl+c
and then restart
node app.
I used mkdir -p /root/.android && touch /root/.android/repositories.cfg to make it works
Output the images in a lossless format such as PNG:
ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png
Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).
I have since found that
-vsync 0
is simpler than-r 10
because it avoids needing to know the frame rate.This is something like what I currently use:
mkdir stills ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
To extract only the key frames (which are likely to be of higher quality post-edit):
ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.
It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1
and outputting as JPEG directly from ffmpeg
.
When you want to fetch max value of a date column from dataframe, just the value without object type or Row object information, you can refer to below code.
table = "mytable"
max_date = df.select(max('date_col')).first()[0]
2020-06-26
instead of Row(max(reference_week)=datetime.date(2020, 6, 26))
You can try something like this. Here on click of image button I toggle the imageview.
holder.imgitem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if(!onclick){
mSparseBooleanArray.put((Integer) view.getTag(), true);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
onclick=true;}
else if(onclick)
{
mSparseBooleanArray.put((Integer) view.getTag(), false);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);
onclick=false;
}
}
});
For your current structure, you could also try the following:
select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country
I think I prefer a union between the two tables, and a group by on the country name as mentioned above.
But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)
Late answer but I have come across a way of passing primitive values by reference by means of closures. It is rather complicated to create a pointer, but it works.
function ptr(get, set) {
return { get: get, set: set };
}
function helloWorld(namePtr) {
console.log(namePtr.get());
namePtr.set('jack');
console.log(namePtr.get())
}
var myName = 'joe';
var myNamePtr = ptr(
function () { return myName; },
function (value) { myName = value; }
);
helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack
In ES6, the code can be shortened to use lambda expressions:
var myName = 'joe';
var myNamePtr = ptr(=> myName, v => myName = v);
helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack
I'm working on Docker with centOS 7, and encountered the same problem.
after looking around, and make several tries, I fixed this problem by installing mongodb, and mongodb-server
yum install mongodb mongodb-server
I don't think this is the best way to produce the minimal container. but I can limit the scope into the following packages
==============================================================================================================
Package Arch Version Repository Size
==============================================================================================================
Installing:
mongodb x86_64 2.6.5-2.el7 epel 57 M
mongodb-server x86_64 2.6.5-2.el7 epel 8.7 M
Installing for dependencies:
boost-filesystem x86_64 1.53.0-18.el7 base 66 k
boost-program-options x86_64 1.53.0-18.el7 base 154 k
boost-system x86_64 1.53.0-18.el7 base 38 k
boost-thread x86_64 1.53.0-18.el7 base 56 k
gperftools-libs x86_64 2.1-1.el7 epel 267 k
libpcap x86_64 14:1.5.3-3.el7_0.1 updates 137 k
libunwind x86_64 1.1-3.el7 epel 61 k
snappy x86_64 1.1.0-3.el7 base 40 k
Visit here to see the complete code. Here you will also find a link for an online terminal where the complete code can be run and the program represents how to extract structure's information(field's name their type & value). Below is the program snippet that only prints the field names.
package main
import "fmt"
import "reflect"
func main() {
type Book struct {
Id int
Name string
Title string
}
book := Book{1, "Let us C", "Enjoy programming with practice"}
e := reflect.ValueOf(&book).Elem()
for i := 0; i < e.NumField(); i++ {
fieldName := e.Type().Field(i).Name
fmt.Printf("%v\n", fieldName)
}
}
/*
Id
Name
Title
*/
a simple way to do that
we can call all model first
@using project.Models
then send your model with viewbag
// for list
ViewBag.Name = db.YourModel.ToList();
// for one
ViewBag.Name = db.YourModel.Find(id);
and in view
// for list
List<YourModel> Name = (List<YourModel>)ViewBag.Name ;
//for one
YourModel Name = (YourModel)ViewBag.Name ;
then easily use this like Model
To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
If you care for it to be in the same order as before you can use a common table expression for that:
;WITH CTE AS (
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
)
SELECT *
FROM CTE
ORDER BY MySortColumn
You can parse the pom file with JDOM (http://www.jdom.org/).
=> check there will be some instance of application installed partially.
=> first of all uninstall that instance from uninstall application.
=> then,clean,Rebuild,and try to deploy.
this solved my issue.hope it helps you too. Best Regards.
REST means working with the standards of the web, and the standard for "secure" transfer on the web is SSL. Anything else is going to be kind of funky and require extra deployment effort for clients, which will have to have encryption libraries available.
Once you commit to SSL, there's really nothing fancy required for authentication in principle. You can again go with web standards and use HTTP Basic auth (username and secret token sent along with each request) as it's much simpler than an elaborate signing protocol, and still effective in the context of a secure connection. You just need to be sure the password never goes over plain text; so if the password is ever received over a plain text connection, you might even disable the password and mail the developer. You should also ensure the credentials aren't logged anywhere upon receipt, just as you wouldn't log a regular password.
HTTP Digest is a safer approach as it prevents the secret token being passed along; instead, it's a hash the server can verify on the other end. Though it may be overkill for less sensitive applications if you've taken the precautions mentioned above. After all, the user's password is already transmitted in plain-text when they log in (unless you're doing some fancy JavaScript encryption in the browser), and likewise their cookies on each request.
Note that with APIs, it's better for the client to be passing tokens - randomly generated strings - instead of the password the developer logs into the website with. So the developer should be able to log into your site and generate new tokens that can be used for API verification.
The main reason to use a token is that it can be replaced if it's compromised, whereas if the password is compromised, the owner could log into the developer's account and do anything they want with it. A further advantage of tokens is you can issue multiple tokens to the same developers. Perhaps because they have multiple apps or because they want tokens with different access levels.
(Updated to cover implications of making the connection SSL-only.)
In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:
db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);
If you don't, unless there's some Join()
override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):
db.Services.Join(db.ServiceAssignments,
s => s.Id,
sa => sa.ServiceId,
(s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);
You can call a stored procedure using the following syntax:
$result = mysql_query('CALL getNodeChildren(2)');
Java 7 and up supports the Path
class (in java.nio package).
You can use this class to convert a string-path to one that works for your current OS.
Using:
Paths.get("\\folder\\subfolder").toString()
on a Unix machine, will give you /folder/subfolder
. Also works the other way around.
https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
DevTools: [network] explain empty bars preceeding request
Investigated further and have identified that there's no significant difference between our Stalled and Queueing ranges. Both are calculated from the delta's of other timestamps, rather than provided from netstack or renderer.
Currently, if we're waiting for a socket to become available:
- we'll call it stalled if some proxy negotiation happened
- we'll call it queuing if no proxy/ssl work was required.
fastest way
function:
var x=function(a,b,c,d){d=[];c=b-a+1;while(c--){d[c]=b--}return d},
theArray=x(lowEnd,highEnd);
or
var arr=[],c=highEnd-lowEnd+1;
while(c--){arr[c]=highEnd--}
EDIT
readable version
var arr = [],
c = highEnd - lowEnd + 1;
while ( c-- ) {
arr[c] = highEnd--
}
Demo
FOR THE DOWNVOTERS
performance
http://jsperf.com/for-push-while-set/2
faster in ie and 3x faster in firefox
only on aipad air the for loop is a little faster.
tested on win8, osx10.8, ubuntu14.04, ipad, ipad air, ipod;
with chrome,ff,ie,safari,mobile safari.
i would like to see the performance on older ie browsers where the for loop isn't that optimized!
Correct and more clear way is :
<div style={{"font-size" : "10px", "height" : "100px", "width" : "100%"}}> My inline Style </div>
It is made more simple by following approach :
// JS
const styleObject = {
"font-size" : "10px",
"height" : "100px",
"width" : "100%"
}
// HTML
<div style={styleObject}> My inline Style </div>
Inline style
attribute expects object. Hence its written in {}
, and it becomes double {{}}
as one is for default react standards.
@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.
This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:
Linux / GNU readlink
solution:
If your script needs to run on Linux only or you know that GNU readlink
is in the $PATH
, use readlink -f
, which conveniently resolves a symlink to its ultimate target:
scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")
Note that GNU readlink
has 3 related options for resolving a symlink to its ultimate target's full path: -f
(--canonicalize
), -e
(--canonicalize-existing
), and -m
(--canonicalize-missing
) - see man readlink
.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f
here, because it is the most well-known one.
Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):
If your script must run on any platform that:
has a readlink
utility, but lacks the -f
option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.
readlink
; note that recent versions of FreeBSD/PC-BSD do support -f
.does not even have readlink
, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).
The following solution, inspired by https://stackoverflow.com/a/1116890/45375,
defines helper shell function, rreadlink()
, which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink
's -e
option, which is similar to the -f
option, except that the ultimate target must exist.
Note: The function is a bash
function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh
), see here.
If readlink
is available, it is used (without options) - true on most modern platforms.
Otherwise, the output from ls -l
is parsed, which is the only POSIX-compliant way to determine a symlink's target.
Caveat: this will break if a filename or path contains the literal substring ->
- which is unlikely, however.
(Note that platforms that lack readlink
may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find
utility supporting the %l
format char. with its -printf
primary; in the interest of brevity the function does NOT try to detect such cases.)
An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink
in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink
; on other platforms (assuming they have bash
), follow the manual installation instructions.
If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.
#!/usr/bin/env bash
# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...
local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH=
# Since we'll be using `command` below for a predictable execution
# environment, we make sure that it has its original meaning.
{ \unalias command; \unset -f command; } &>/dev/null
while :; do # Resolve potential symlinks until the ultimate target is found.
[[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
fname=$(command basename -- "$target") # Extract filename.
[[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
if [[ -L $fname ]]; then
# Extract [next] target path, which is defined
# relative to the symlink's own directory.
if [[ -n $readlinkexe ]]; then # Use `readlink`.
target=$("$readlinkexe" -- "$fname")
else # `readlink` utility not available.
# Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant
# way to determine a symlink's target. Hypothetically, this can break with
# filenames containig literal ' -> ' and embedded newlines.
target=$(command ls -l -- "$fname")
target=${target#* -> }
fi
continue # Resolve [next] symlink target.
fi
break # Ultimate target reached.
done
targetDir=$(command pwd -P) # Get canonical dir. path
# Output the ultimate target's canonical path.
# Note that we manually resolve paths ending in /. and /.. to make sure we
# have a normalized path.
if [[ $fname == '.' ]]; then
command printf '%s\n' "${targetDir%/}"
elif [[ $fname == '..' ]]; then
# Caveat: something like /var/.. will resolve to /private (assuming
# /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
command printf '%s\n' "$(command dirname -- "${targetDir}")"
else
command printf '%s\n' "${targetDir%/}/$fname"
fi
)
# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")
I had the same issue but solved it by using Ubuntu.
python -m pip install pyaudio
brew install portaudio
brew link portaudio
Old question but i feel i should add the following, even more because .net 4.0 had already launched at the time the question was written.
Starting with .net 4.0 there is the namespace System.Collections.Concurrent
which includes collections that are thread-safe.
The collection System.Collections.Concurrent.ConcurrentDictionary<>
does exactly what you want. It has the AddOrUpdate()
method with the added advantage of being thread-safe.
If you're in a high-performance scenario and not handling multiple threads the already given answers of map[key] = value
are faster.
In most scenarios this performance benefit is insignificant. If so i'd advise to use the ConcurrentDictionary because:
Check that you have the latest version of the SDK installed in either C:\Program Files\Java
or C:\Program Files (x86)\Java
Then go to VS2015 and follow the path tools - options - Xamarin - Android settings and in the section JDK location select change and go to look for the version you have either x64 or x32.
Use obj[0].nick and you will get desired result,
If you really mean any and ASCII (not e.g. all Unicode characters):
xxx[\x00-\x7F]+xxx
JavaScript example:
var re = /xxx[\x00-\x7F]+xxx/;
re.test('xxxabcxxx')
// true
re.test('xxx???xxx')
// false
Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.
Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?
This seems to be related to Unable to install Python libraries
See Dominique Barton's answer:
Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.
On Debian-based systems I'd try:
apt-get update && apt-get upgrade python-pip
On Red Hat Linux-based systems:
yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)
On Mac:
sudo easy_install -U pip
You can also try to update
openssl
separately.
Had a similar problem to yours. What we had to do is use the document.domain solution found here:
Ways to circumvent the same-origin policy
We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:
GROUP BY YEAR(t.summaryDateTime), MONTH(t.summaryDateTime);
is what you want.
Mark, if you check the nerddinner MVC example the logic is pretty much the same.
You only need to retrieve the cookie and set it in the current session.
Global.asax.cs
public override void Init()
{
this.AuthenticateRequest += new EventHandler(WebApiApplication_AuthenticateRequest);
base.Init();
}
void WebApiApplication_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
SampleIdentity id = new SampleIdentity(ticket);
GenericPrincipal prin = new GenericPrincipal(id, null);
HttpContext.Current.User = prin;
}
enter code here
You'll have to define your "SampleIdentity" class, which you can borrow from the nerddinner project.
In Java, you can verify using Object utils.
import static java.util.Objects.isNull;
if(IsNull(yourObject)){
//your block here
}
Static classes in languages like C# exist because there are no other top-level constructs to group data and functions. In JavaScript, however, they do and so it is much more natural to just declare an object like you did. To more closely mimick the class syntax, you can declare methods like so:
const myStaticClass = {
property: 10,
method() {
}
}
This works best:
git fetch origin specific_commit
git checkout -b temp FETCH_HEAD
name "temp" whatever you want...this branch might be orphaned though
You can use axis
:
> axis(side=1, at=c(0:23))
That is, something like this:
plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()
I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).
Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.
You can solve your problem with help of Attribute routing
Controller
[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }
URI in jquery
api/category/1
Route Configuration
using System.Web.Http;
namespace WebApplication
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
}
}
and your default routing is working as default convention-based routing
Controller
public string Get(int id)
{
return "object of id id";
}
URI in Jquery
/api/records/1
Route Configuration
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Review article for more information Attribute routing and onvention-based routing here & this
I needed the count of all checkboxes which are checked. Instead of writing a loop i did this
$(".myCheckBoxClass:checked").length;
Compare it with the total number of checkboxes to see if they are equal. Hope it will help someone
for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0)
starts with [
character).
Hope this helps.
txtarea = new JTextArea();
txtarea.setRows(25);
txtarea.setColumns(25);
txtarea.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane (txtarea);
panel2.add(scroll); //Object of Jpanel
Above given lines automatically shows you both horizontal & vertical Scrollbars..
When attempting to export data using the accepted answer I got an error:
ERROR 1235 (42000) at line 3367: This version of MySQL doesn't yet support 'multiple triggers with the same action time and event for one table'
As mentioned above:
mysqldump --no-create-info
Will export the data but it will also export the create trigger statements. If like me your outputting database structure (which also includes triggers) with one command and then using the above command to get the data you should also use '--skip-triggers'.
So if you want JUST the data:
mysqldump --no-create-info --skip-triggers
We use couchdb in production and have since just before the project went under the Apache umbrella.
We use it to store everything that we might otherwise use a dbms, plus all sorts of unstructured data. Personally, I really like how you can just throw all sorts of data into it and use the views to cull what you don't need depending on the situation.
The hardest part was moving away from the dbms mindset. We wrote our own migration utils when the storage format changed just to be safe, so that wasn't really a problem.
We haven't had any negative experiences yet, but then again we haven't had the setup under any kind of huge load. I think things would work pretty well since we have two slave type servers that replicate from a single master server that gets all of the writes. I'm pretty sure that we don't have to do it that way for replication to work correctly, but it's how we set it up in the beginning and it stuck.
You can convert .jar file to .exe on these ways:
(source: viralpatel.net)
1- JSmooth .exe wrapper:
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a web site.
JSmooth provides a variety of wrappers for your java application, each of them having their own behaviour: Choose your flavour!
Download: http://jsmooth.sourceforge.net/
2- JarToExe 1.8
Jar2Exe is a tool to convert jar files into exe files.
Following are the main features as describe in their website:
Download: http://www.brothersoft.com/jartoexe-75019.html
3- Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows exe file, indistinguishable from a native application. Simply double-clicking the exe file will invoke the Java Runtime Environment and launch your application.
Download: http://mpowers.net/executor/
EDIT: The above link is broken, but here is the page (with working download) from the Internet Archive. http://web.archive.org/web/20090316092154/http://mpowers.net/executor/
4- Advanced Installer
Advanced Installer lets you create Windows MSI installs in minutes. This also has Windows Vista support and also helps to create MSI packages in other languages.
Download: http://www.advancedinstaller.com/
Let me know other tools that you have used to convert JAR to EXE.
JsonP only works with type: GET,
More info (PHP) http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/
.NET: http://www.west-wind.com/weblog/posts/2007/Jul/04/JSONP-for-crosssite-Callbacks
I fixed this error by inserting these lines of code:
<dependency>
<groupId>junit</groupId> <!-- NOT org.junit here -->
<artifactId>junit-dep</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
into <dependencies> node.
more details refer to: http://mvnrepository.com/artifact/junit/junit-dep/4.8.2
Thanks everyone who have answered.I have seen all answers and to try to make it easy for everyone
Step 1: Type edit environment and select the option shown
Step 2: Select Path and click on edit
Step 3: In the end add the below statement(you can avoid the first ; if its already there)
;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd
Step 4:- Click on ok
Step 5 **:- One of the important step which is highlighted by one of the users. thanks to him. Please, **CLOSE command prompt and REOPEN then try to write git.
**
**
Here is the magic
\n
is an escape sequence, denoted by the backslash. A normal forward slash, such as /n
will not do the job. In your code you are using /n
instead of \n
.
I was just wondering why we can't call
await
from within a constructor directly.
I believe the short answer is simply: Because the .Net team has not programmed this feature.
I believe with the right syntax this could be implemented and shouldn't be too confusing or error prone. I think Stephen Cleary's blog post and several other answers here have implicitly pointed out that there is no fundamental reason against it, and more than that - solved that lack with workarounds. The existence of these relatively simple workarounds is probably one of the reasons why this feature has not (yet) been implemented.
function tinyFriends() {
let myFriends = ["Mukit", "Ali", "Umor", "sabbir"]
let smallestFridend = myFriends[0];
for (i = 0; i < myFriends.length; i++) {
if (myFriends[i] < smallestFridend) {
smallestFridend = myFriends[i];
}
}
return smallestFridend
}
window.location.href = "URL2"
inside a JS block on the page or in an included file; that's assuming you really want to do it on the client. Usually, the server sends the redirect via a 300-series response.
To expand a little more, there are two kinds of constructors: instance initializers (.ctor), type initializers (.cctor). Build the code below, and explore the IL code in ildasm.exe. You will notice that the static field 'b' will be initialized through .cctor() whereas the instance field will be initialized through .ctor()
internal sealed class CtorExplorer
{
protected int a = 0;
protected static int b = 0;
}
I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
url = $sce.trustAsResourceUrl(url);
$http.jsonp(url, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});
json.loads
take a string as input and returns a dictionary as output.json.dumps
take a dictionary as input and returns a string as output.If you need to convert JSON data into a python object, it can do so with Python3
, in one line without additional installations, using SimpleNamespace
and object_hook
:
import json
from types import SimpleNamespace
string = '{"foo":3, "bar":{"x":1, "y":2}}'
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))
print(x.foo)
print(x.bar.x)
print(x.bar.y)
output:
3
1
2
JSON object: data.json
{
"foo": 3,
"bar": {
"x": 1,
"y": 2
}
}
import json
from types import SimpleNamespace
with open("data.json") as fh:
string = fh.read()
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))
print(x.foo)
print(x.bar.x)
print(x.bar.y)
output:
3
1
2
import json
from types import SimpleNamespace
import requests
r = requests.get('https://api.github.com/users/MilovanTomasevic')
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(r.text, object_hook=lambda d: SimpleNamespace(**d))
print(x.name)
print(x.company)
print(x.blog)
output:
Milovan Tomaševic
NLB
milovantomasevic.com
For more beautiful and faster access to JSON response from API, take a look at this response.
On Ubuntu, I had to sudo apt-get update
and then the nodejs install worked.
Spring uses an special logic for resolving this kind of circular dependencies with singleton beans. But this won't apply to other scopes. There is no elegant way of breaking this circular dependency, but a clumsy option could be this one:
@Component("bean1")
@Scope("view")
public class Bean1 {
@Autowired
private Bean2 bean2;
@PostConstruct
public void init() {
bean2.setBean1(this);
}
}
@Component("bean2")
@Scope("view")
public class Bean2 {
private Bean1 bean1;
public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
}
}
Anyway, circular dependencies are usually a symptom of bad design. You would think again if there is some better way of defining your class dependencies.
In
from math import sqrt
Using sqrt(4) works perfectly well. You need to only use math.sqrt(4) when you just use "import math".
Some thing like this should also work
import numpy as np
def proper_round(a):
'''
given any real number 'a' returns an integer closest to 'a'
'''
a_ceil = np.ceil(a)
a_floor = np.floor(a)
if np.abs(a_ceil - a) < np.abs(a_floor - a):
return int(a_ceil)
else:
return int(a_floor)
WebDriver's driver.switchTo().frame()
method takes one of the three possible arguments:
Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index
0
, the second at index1
and the third at index2
. Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.
Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.
A previously found WebElement
.
Select a frame using its previously located WebElement.
Get the frame by it's id/name or locate it by driver.findElement()
and you'll be good.
Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t
. I am glad that you did.
Anyways, You have a .c
source file, and most of the code looks as per C standards, except that #include <iostream>
and using namespace std;
C equivalent for the built-in functions of C++ standard #include<iostream>
can be availed through #include<stdio.h>
#include <iostream>
with #include <stdio.h>
, delete using namespace std;
With #include <iostream>
taken off, you would need a C standard alternative for cout << endl;
, which can be done by printf("\n");
or putchar('\n');
Out of the two options, printf("\n");
works the faster as I observed.
When used printf("\n");
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.031s
user 0m0.030s
sys 0m0.030s
When used putchar('\n');
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.047s
user 0m0.030s
sys 0m0.030s
Compiled with Cygwin gcc (GCC) 4.8.3
version. results averaged over 10 samples. (Took me 15 mins)
Typically, a Json object would contain your values (including arrays) as named fields within. So, something like:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName",ja);
Which in JSON will be {"arrayName":[...]}.
Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)
#include <iostream>
int main()
{
std::cout<<"Hello World!\n";
return 0;
}
I had a similar issue when I switched from IntellijIDEA to Eclipse. It can be done in the following steps. Go to Window > Preferences > Java > Editor > Content Assist and type ._abcdefghijklmnopqrstuvwxyzS in the Auto activation triggers for Java field
Without code and mappings for your transactions, it'll be next to impossible to investigate the problem.
However, to get a better handle as to what causes the problem, try the following:
Hope that helps.
For a pure Ruby solution combine URI.parse
with CGI.parse
(this can be used even if Rails/Rack etc. are not required):
CGI.parse(URI.parse(url).query)
# => {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }
I have found a solution by myself. I use the PDANet tool to find the driver automatically.
You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href
.
Example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
window.location.href = 'https://website.com/my-account';
}
};
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
You can also use an express framework
app.get("/:id",function(req,res)
{
var id = req.params.id;
res.render("home.ejs",{identity : id});
});
Express file, which receives a JS variable identity from node.js
<a href = "/any_route/<%=identity%>
includes identity JS variable into your href
without a trouble enter
From the documentation on http://curl.haxx.se/docs/httpscripting.html :
HTTP Authentication
curl --user name:password http://www.example.com
Put a file to a HTTP server with curl:
curl --upload-file uploadfile http://www.example.com/receive.cgi
Send post data with curl:
curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi
<div class="scrollingDiv">foo</div>
div.scrollingDiv
{
overflow:scroll;
}
Define "necessary".
It is necessary if you want the browser to know what the type of the file is. PHP automatically sets the Content-Type
header to text/html
if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send:
<b><i>test</i></b>
a Content-Type: text/html
would output:
test
whereas Content-Type: text/plain
would output:
<b><i>test</i></b>
TLDR Version: If you really are only outputing text then it doesn't really matter, but it IS wrong.
The import form and the module declaration need to agree about the shape of the module, about what it exports.
When you write (a suboptimal practice for importing JSON since TypeScript 2.9 when targeting compatible module formatssee note)
declare module "*.json" {
const value: any;
export default value;
}
You are stating that all modules that have a specifier ending in .json
have a single export named default
.
There are several ways you can correctly consume such a module including
import a from "a.json";
a.primaryMain
and
import * as a from "a.json";
a.default.primaryMain
and
import {default as a} from "a.json";
a.primaryMain
and
import a = require("a.json");
a.default.primaryMain
The first form is the best and the syntactic sugar it leverages is the very reason JavaScript has default
exports.
However I mentioned the other forms to give you a hint about what's going wrong. Pay special attention to the last one. require
gives you an object representing the module itself and not its exported bindings.
So why the error? Because you wrote
import a = require("a.json");
a.primaryMain
And yet there is no export named primaryMain
declared by your "*.json"
.
All of this assumes that your module loader is providing the JSON as the default
export as suggested by your original declaration.
Note: Since TypeScript 2.9, you can use the --resolveJsonModule
compiler flag to have TypeScript analyze imported .json
files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. This is not supported for certain target module formats.
UPDATE: From the comments this answer seems to be out of date
The Flutter documentation points out where you can change the display name of your application for both Android and iOS. This may be what you are looking for:
For Android
It seems you have already found this in the AndroidManifest.xml
as the application
entry.
Review the default App Manifest file AndroidManifest.xml located in /android/app/src/main/ and verify the values are correct, especially:
application: Edit the application tag to reflect the final name of the app.
For iOS
See the Review Xcode project settings
section:
Navigate to your target’s settings in Xcode:
In Xcode, open Runner.xcworkspace in your app’s ios folder.
To view your app’s settings, select the Runner project in the Xcode project navigator. Then, in the main view sidebar, select the Runner target.
Select the General tab. Next, you’ll verify the most important settings:
Display Name: the name of the app to be displayed on the home screen and elsewhere.
The newer android phones in the market like HTC one, Xperia Z etc have resolutions in the >480dpi range, putting them in the new xxhdpi class as well. The new assets might be useful for them too.
Python String rindex() Method
Description
Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].
Syntax
Following is the syntax for rindex() method -
str.rindex(str, beg=0 end=len(string))
Parameters
str - This specifies the string to be searched.
beg - This is the starting index, by default its 0
len - This is ending index, by default its equal to the length of the string.
Return Value
This method returns last index if found otherwise raises an exception if str is not found.
Example
The following example shows the usage of rindex() method.
Live Demo
str1 = "this is string example....wow!!!";
str2 = "is";
print str1.rindex(str2)
print str1.index(str2)
When we run above program, it produces following result -
5
2
HTML DOM querySelectorAll() method seems apt here.
W3School Link given here
Syntax (As given in W3School)
document.querySelectorAll(CSS selectors)
So the answer.
document.querySelectorAll("[name^=q1_]")
Edit:
Considering FLX's suggestion adding link to MDN here
May be the best way to utilize "download" button is to use JavaScript players, such as Videojs (http://docs.videojs.com/) or MediaElement.js (http://www.mediaelementjs.com/)
They do not have download button by default as a rule and moreover allow you to customize visible control buttons of the player.
Expanded from @SeaBrightSystems answer, you could try this:
$s1 = "textasstringwoohoo";
$arr = str_split($s1); //$arr now has character array
You can rather pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
data: "param1=getAccNos¶m2="+encodeURIComponent('Dolce & Gabbana') OR
var someValue = 'Dolce & Gabbana';
data : "param1=getAccNos¶m2="+encodeURIComponent(someValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
Try this. I set the blue box to float right, gave left and right a fixed height, and added a white border on the right of the left div. Also added rounded corners to more match your example (These won't work in ie 8 or less). I also took out the position: relative. You don't need it. Block level elements are set to position relative by default.
See it here: http://jsfiddle.net/ZSgLJ/
#left {
float: left;
width: 44%;
margin: 0;
padding: 0;
border-right: 1px solid white;
height:400px;
}
#right {
position: relative;
float: right;
width: 49%;
margin: 0;
padding: 0;
height:400px;
}
#blue_box {
background-color:blue;
border-radius: 10px;
-moz-border-radius:10px;
-webkit-border-radius: 10px;
width: 45%;
min-width: 400px;
max-width: 600px;
padding: 2%;
float: right;
}
On Servlet 3.0 or newer you could just specify
<web-app ...>
<error-page>
<location>/general-error.html</location>
</error-page>
</web-app>
But as you're still on Servlet 2.5, there's no other way than specifying every common HTTP error individually. You need to figure which HTTP errors the enduser could possibly face. On a barebones webapp with for example the usage of HTTP authentication, having a disabled directory listing, using custom servlets and code which can possibly throw unhandled exceptions or does not have all methods implemented, then you'd like to set it for HTTP errors 401, 403, 500 and 503 respectively.
<error-page>
<!-- Missing login -->
<error-code>401</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Forbidden directory listing -->
<error-code>403</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Missing resource -->
<error-code>404</error-code>
<location>/Error404.html</location>
</error-page>
<error-page>
<!-- Uncaught exception -->
<error-code>500</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Unsupported servlet method -->
<error-code>503</error-code>
<location>/general-error.html</location>
</error-page>
That should cover the most common ones.
3.https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html
getExternalStoragePublicDirectory()
is deprecated.
To get the download folder from a Fragment
,
val downloadFolder = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
From an Activity
,
val downloadFolder = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
downloadFolder.listFiles()
will list the File
s.
downloadFolder?.path
will give you the String path of the download folder.
This is one way to do it:
Fiddle here: http://jsfiddle.net/4Mvan/1/
HTML:
<div class='container'>
<a href='#'>
<img class='resize_fit_center'
src='http://i.imgur.com/H9lpVkZ.jpg' />
</a>
</div>
CSS:
.container {
margin: 10px;
width: 115px;
height: 115px;
line-height: 115px;
text-align: center;
border: 1px solid red;
}
.resize_fit_center {
max-width:100%;
max-height:100%;
vertical-align: middle;
}
they are two different things..
[]
is declaring an Array:
given, a list of elements held by numeric index.
{}
is declaring a new object:
given, an object with fields with Names and type+value,
some like to think of it as "Associative Array".
but are not arrays, in their representation.
You can read more @ This Article
F=code.c
REV=123
svn diff -c $REV $F | patch -R -p0 \
&& svn commit -m "undid rev $REV" $F
SPSS can also read .dta files and export them to .csv, but that costs money. PSPP, an open source version of SPSS, which is rough, might also be able to read/export .dta files.
alternatively you could use ctypes witch would look something like this
import ctypes
def f(a):
a.value=2398 ## resign the value in a function
a = ctypes.c_int(0)
print("pre f", a)
f(a)
print("post f", a)
as a is a c int and not a python integer and apperently passed by reference. however you have to be carefull as strange things could happen and is therefor not advised
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
NSArray *keys = [dictionary allKeys];
NSArray *values = [dictionary allValues];
Try Catch exists via workaround in VBScript:
Class CFunc1
Private Sub Class_Initialize
WScript.Echo "Starting"
Dim i : i = 65535 ^ 65535
MsgBox "Should not see this"
End Sub
Private Sub CatchErr
If Err.Number = 0 Then Exit Sub
Select Case Err.Number
Case 6 WScript.Echo "Overflow handled!"
Case Else WScript.Echo "Unhandled error " & Err.Number & " occurred."
End Select
Err.Clear
End Sub
Private Sub Class_Terminate
CatchErr
WScript.Echo "Exiting"
End Sub
End Class
Dim Func1 : Set Func1 = New CFunc1 : Set Func1 = Nothing
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
python <main module>.py
does not work with relative importThe problem is relative import does not work when you run a __main__
module from the command line
python <main_module>.py
It is clearly stated in PEP 338.
The release of 2.5b1 showed a surprising (although obvious in retrospect) interaction between this PEP and PEP 328 - explicit relative imports don't work from a main module. This is due to the fact that relative imports rely on
__name__
to determine the current module's position in the package hierarchy. In a main module, the value of__name__
is always'__main__'
, so explicit relative imports will always fail (as they only work for a module inside a package).
The issue isn't actually unique to the -m switch. The problem is that relative imports are based on
__name__
, and in the main module,__name__
always has the value__main__
. Hence, relative imports currently can't work properly from the main module of an application, because the main module doesn't know where it really fits in the Python module namespace (this is at least fixable in theory for the main modules executed through the -m switch, but directly executed files and the interactive interpreter are completely out of luck).
To understand further, see Relative imports in Python 3 for the detailed explanation and how to get it over.
$(function() {
$('#sortable').sortable({
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
change: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var index = ui.placeholder.index();
if (start_pos < index) {
$('#sortable li:nth-child(' + index + ')').addClass('highlights');
} else {
$('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
}
},
update: function(event, ui) {
$('#sortable li').removeClass('highlights');
}
});
});
I went into Windows Update & looked at the update history, knowing the server patching is kept up-to-date. I scanned down for .NET updates and it showed me exactly which versions had had updates, which allowed me to conclude which versions were installed.
I like @Luca's answer as i think it's the most elegant.
However I don't want my colours specified in ARGB. I'd rather RGBA + also i needed to hack in the case of dealing with strings that specify 1 character for each of the channels "#FFFA".
This version also adds error throwing + strips the '#' character if it's included in the string. Here is my modified form for Swift.
public enum ColourParsingError: Error
{
case invalidInput(String)
}
extension UIColor {
public convenience init(hexString: String) throws
{
let hexString = hexString.replacingOccurrences(of: "#", with: "")
let hex = hexString.trimmingCharacters(in:NSCharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.count
{
case 3: // RGB (12-bit)
(r, g, b,a) = ((int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17,255)
//iCSS specification in the form of #F0FA
case 4: // RGB (24-bit)
(r, g, b,a) = ((int >> 12) * 17, (int >> 8 & 0xF) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(r, g, b, a) = (int >> 16, int >> 8 & 0xFF, int & 0xFF,255)
case 8: // ARGB (32-bit)
(r, g, b, a) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
throw ColourParsingError.invalidInput("String is not a valid hex colour string: \(hexString)")
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
Using Kotlin, we can achieve by doing the following
Handler().postDelayed({
// do something after 1000ms
}, 1000)
There should be
$('.send_upload')
but not $('.upload')
if you just want the number of occurences then you can do this, $ grep -c "string_to_count" file_name
There are two options here.
One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase.
Another is to use the --rebase-merges
option on git rebase
, which is described as follows from the manual:
By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually."
I'm using GDB7.1.1, as --help
shows:
gdb [options] --args executable-file [inferior-arguments ...]
IMHO, the order is a bit unintuitive at first.
Seems to be a common Windows problem. This fixed it for me:
Nodejs cannot find installed module on Windows?
"Add an environment variable called NODE_PATH
and set it to %USERPROFILE%\Application Data\npm\node_modules
(Windows XP), %AppData%\npm\node_modules
(Windows 7), or wherever npm ends up installing the modules on your Windows flavor. To be done with it once and for all, add this as a System variable in the Advanced tab of the System Properties dialog (run control.exe sysdm.cpl,System,3)."
Note that you can't actually use another environment variable within the value of NODE_PATH
. That is, don't just copy and paste that string above, but set it to an actual resolved path like C:\Users\MYNAME\AppData\Roaming\npm\node_modules
In my case the element that generated the Exception was a button belonging to a form. I replaced
WebElement btnLogin = driver.findElement(By.cssSelector("button"));
btnLogin.click();
with
btnLogin.submit();
My environment was chromedriver windows 10
If you want to search deleted record (Soft Deleted Record), do't user Eloquent Model Query. Instead use Db::table query e.g Instead of using Below:
$stu = Student::where('rollNum', '=', $rollNum . '-' . $nursery)->first();
Use:
$stu = DB::table('students')->where('rollNum', '=', $newRollNo)->first();
Include in your manifest file under activity which you want to display .But make sure not using Full screen Activity
android:windowSoftInputMode="adjustPan"
I also faced that problem and there are two ways to solve this in laravel.
first one is you can set the default value as null. I will show you an example:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('gender');
$table->string('slug');
$table->string('pic')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
as the above example, you can set nullable()
for that feature. then when you are inserting data MySQL set the default value as null.
second one is in your model set your input field in protected $fillable
field. as example:
protected $fillable = [
'name', 'email', 'password', 'slug', 'gender','pic'
];
I think the second one is fine than the first one and also you can set nullable feature as well as fillable in the same time without a problem.
If you are designing your Javafx application using SceneBuilder
then use -fx-text-fill
(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield
.
I came here for the same problem and solved it in this way.
So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:
These options work great with me and I can start apache service without errors.
The other option is to change apache listen port from httpd.conf and set another port number.
Hope this solution helps anyone who face the same problem again.
There are many ways by which you can access one controller into another.
class Test1 extends CI_controller
{
function testfunction(){
return 1;
}
}
Then create another class, and include first Class in it, and extend it with your class.
include 'Test1.php';
class Test extends Test1
{
function myfunction(){
$this->test();
echo 1;
}
}
I agree with Sam and Xaser and have actually taken this a bit farther. I don't think you should be implementing the INotifyPropertyChanged
interface in a UserControl
at all...the control is already a DependencyObject
and therefore already comes with notifications. Adding INotifyPropertyChanged
to a DependencyObject
is redundant and "smells" wrong to me.
What I did is implement both properties as DependencyProperties
, as Sam suggests, but then simply had the PropertyChangedCallback
from the "first" dependency property alter the value of the "second" dependency property. Since both are dependency properties, both will automatically raise change notifications to any interested subscribers (e.g. data binding etc.)
In this case, dependency property A is the string InviteText
, which triggers a change in dependency property B, the Visibility
property named ShowInvite
. This would be a common use case if you have some text that you want to be able to hide completely in a control via data binding.
public string InviteText
{
get { return (string)GetValue(InviteTextProperty); }
set { SetValue(InviteTextProperty, value); }
}
public static readonly DependencyProperty InviteTextProperty =
DependencyProperty.Register("InviteText", typeof(string), typeof(InvitePrompt), new UIPropertyMetadata(String.Empty, OnInviteTextChanged));
private static void OnInviteTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
InvitePrompt prompt = d as InvitePrompt;
if (prompt != null)
{
string text = e.NewValue as String;
prompt.ShowInvite = String.IsNullOrWhiteSpace(text) ? Visibility.Collapsed : Visibility.Visible;
}
}
public Visibility ShowInvite
{
get { return (Visibility)GetValue(ShowInviteProperty); }
set { SetValue(ShowInviteProperty, value); }
}
public static readonly DependencyProperty ShowInviteProperty =
DependencyProperty.Register("ShowInvite", typeof(Visibility), typeof(InvitePrompt), new PropertyMetadata(Visibility.Collapsed));
Note I'm not including the UserControl
signature or constructor here because there is nothing special about them; they don't need to subclass from INotifyPropertyChanged
at all.
You can use the following command
stat -c "%a %n" *
Also you can use any filename
or directoryname
instead of *
to get a specific result.
On Mac, you can use
stat -f '%A %N' *
Release 3.2 of commons-lang
will have FastDateParser
class that is a thread-safe substitute of SimpleDateFormat
for Gregorian calendar. See LANG-909
for more information.
Here you can find how to set path to JDK for Glassfish: http://www.devdaily.com/blog/post/java/fixing-glassfish-jdk-path-problem-solved
Check
glassfish\config\asenv.bat
where java path is configured
REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16
Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class
myObj:any = {
doSomething: function () { console.log('doing something'); return 'doing something'; },
};
myArray:any;
constructor() { }
ngOnInit() {
this.myArray = [this.myObj];
}
You can use it in template html file as following:
<div>test-1: {{ myObj?.doSomething()}}</div>
<div>test-2: {{ myArray[0].doSomething()}}</div>
<div>test-3: {{ myArray[2]?.doSomething()}}</div>
I was facing the same problem. The problem is with the onclick
function. There should not be any problem with the function getData
. It worked by making the onclick
function return false.
<form method="POST">
<button name="data" onclick="getData(); return false">Click</button>
</form>
You can use jQuery UI and do something like this
Html:
<button id="callConfirm">Confirm!</button>
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>?
Javascript:
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons : {
"Confirm" : function() {
alert("You have confirmed!");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#callConfirm").on("click", function(e) {
e.preventDefault();
$("#dialog").dialog("open");
});
?
i just changed my target .net framework and it worked .in my case i changed from .net 4.7 to .net 4. Right click your solution and select properties selct properties
Click Application >> Target Framework
Call SYS_CONTEXT
to get the current schema. From Ask Tom "How to get current schema:
select sys_context( 'userenv', 'current_schema' ) from dual;
Call
Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call. Call has no effect at the command-line when used outside of a script or batch file. https://technet.microsoft.com/en-us/library/bb490873.aspx
Start
Starts a separate Command Prompt window to run a specified program or command. Used without parameters, start opens a second command prompt window. https://technet.microsoft.com/en-us/library/bb491005.aspx
Java has Reflection (java.reflection.*), but I would suggest looking into a library like Apache Beanutils, it will make the process much less hairy than using reflection directly.
Kinda surprised nobody's pointed out the direct way to do it, which is easy enough.
double roundToDecimalPlaces(double value, int decimalPlaces)
{
double shift = Math.pow(10,decimalPlaces);
return Math.round(value*shift)/shift;
}
Pretty sure this does not do half-even rounding though.
For what it's worth, half-even rounding is going to be chaotic and unpredictable any time you mix binary-based floating-point values with base-10 arithmetic. I'm pretty sure it cannot be done. The basic problem is that a value like 1.105 cannot be represented exactly in floating point. The floating point value is going to be something like 1.105000000000001, or 1.104999999999999. So any attempt to perform half-even rounding is going trip up on representational encoding errors.
IEEE floating point implementations will do half-rounding, but they do binary half-rounding, not decimal half-rounding. So you're probably ok
Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.
You actually can do this but it's a bit of a bodge.
First off create a new Page class which looks something like the following:
public partial class NoRenderPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
public override void VerifyRenderingInServerForm(Control control)
{
//Allows for printing
}
public override bool EnableEventValidation
{
get { return false; }
set { /*Do nothing*/ }
}
}
Does not need to have an .ASPX associated with it.
Then in the control you wish to render you can do something like the following.
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
var page = new NoRenderPage();
page.DesignerInitialize();
var form = new HtmlForm();
page.Controls.Add(form);
form.Controls.Add(pnl);
controlToRender.RenderControl(hw);
Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.
If you want to merge the filters (eg. CSV and Excel files), use this formula:
OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";
Or if you want to see XML or PDF files in one time use this:
of.Filter = @" XML or PDF |*.xml;*.pdf";
By using fabric js we can solve this security error issue in IE.
function getBase64FromImageUrl(URL) {
var canvas = new fabric.Canvas('c');
var img = new Image();
img.onload = function() {
var canvas1 = document.createElement("canvas");
canvas1.width = this.width;
canvas1.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL({format: "png"});
};
img.src = URL;
}
For case where you are using custom fonts, but do not have bold typeface for the font you can use:
myTextView.setText(Html.fromHtml("<b>" + myText + "</b>");
There's also another way to do this-
select TO_CHAR(SA.[RequestStartDate] , 'DD/MM/YYYY') as RequestStartDate from ... ;
I got this error when I made a request with picture.type(full_picture)
:
"(#100) For field 'picture': type must be one of the following values: small, normal, album, large, square"
When I make the request with picture.type(album)
and picture.type(square)
, responses me with an image 50x50 pixel size.
When I make the request with picture.type(large)
, responses me with an image 200x200 pixel size.
When I make the request with picture.width(800)
, responses me with an image 477x477 pixel size.
with picture.width(250)
, responses 320x320.
with picture.width(50)
, responses 50x50.
with picture.width(100)
, responses 100x100.
with picture.width(150)
, responses 160x160.
I think that facebook gives the images which resized variously when the user first add that photo.
What I see here the API for requesting user Image does not support resizing the image requested. It gives the nearest size of image, I think.
I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:
#!/usr/bin/python
def expand_dnsname(dnsname):
from socket import getaddrinfo
from dns import reversename, resolver
namelist = [ ]
# expand hostname into dict of ip addresses
iplist = dict()
for answer in getaddrinfo(dnsname, 80):
ipa = str(answer[4][0])
iplist[ipa] = 0
# run through the list of IP addresses to get hostnames
for ipaddr in sorted(iplist):
rev_name = reversename.from_address(ipaddr)
# run through all the hostnames returned, ignoring the dnsname
for answer in resolver.query(rev_name, "PTR"):
name = str(answer)
if name != dnsname:
# add it to the list of answers
namelist.append(name)
break
# if no other choice, return the dnsname
if len(namelist) == 0:
namelist.append(dnsname)
# return the sorted namelist
namelist = sorted(namelist)
return namelist
namelist = expand_dnsname('google.com.')
for name in namelist:
print name
Which, when I run it, lists a few 1e100.net hostnames:
In your CSS add this:
input {-webkit-appearance: none; box-shadow: none !important; }
:-webkit-autofill { color: #fff !important; }
Only for Chrome! :)
There are some great answers already, but none of them address a complete list of what the __future__
statement currently supports.
Put simply, the __future__
statement forces Python interpreters to use newer features of the language.
The features that it currently supports are the following:
nested_scopes
Prior to Python 2.1, the following code would raise a NameError:
def f():
...
def g(value):
...
return g(value-1) + 1
...
The from __future__ import nested_scopes
directive will allow for this feature to be enabled.
generators
Introduced generator functions such as the one below to save state between successive function calls:
def fib():
a, b = 0, 1
while 1:
yield b
a, b = b, a+b
division
Classic division is used in Python 2.x versions. Meaning that some division statements return a reasonable approximation of division ("true division") and others return the floor ("floor division"). Starting in Python 3.0, true division is specified by x/y
, whereas floor division is specified by x//y
.
The from __future__ import division
directive forces the use of Python 3.0 style division.
absolute_import
Allows for parenthesis to enclose multiple import
statements. For example:
from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,
LEFT, DISABLED, NORMAL, RIDGE, END)
Instead of:
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \
LEFT, DISABLED, NORMAL, RIDGE, END
Or:
from Tkinter import Tk, Frame, Button, Entry, Canvas, Text
from Tkinter import LEFT, DISABLED, NORMAL, RIDGE, END
with_statement
Adds the statement with
as a keyword in Python to eliminate the need for try/finally
statements. Common uses of this are when doing file I/O such as:
with open('workfile', 'r') as f:
read_data = f.read()
print_function
:
Forces the use of Python 3 parenthesis-style print()
function call instead of the print MESSAGE
style statement.
unicode_literals
Introduces the literal syntax for the bytes
object. Meaning that statements such as bytes('Hello world', 'ascii')
can be simply expressed as b'Hello world'
.
generator_stop
Replaces the use of the StopIteration
exception used inside generator functions with the RuntimeError
exception.
One other use not mentioned above is that the __future__
statement also requires the use of Python 2.1+ interpreters since using an older version will throw a runtime exception.
If you need multiple columns to group by, follow this model. Here I am conducting a count by status
and type
:
db.BusinessProcess.aggregate({
"$group": {
_id: {
status: "$status",
type: "$type"
},
count: {
$sum: 1
}
}
})
Apache Commons IO Charsets class can come in handy:
String utf8String = new String(org.apache.commons.io.Charsets.ISO_8859_1.encode(latinString).array())
if (isset($_POST['submit'])) {
for($i = 0; $i<= 3; $i++){
if(isset($_POST['books'][$i]))
$book .= ' '.$_POST['books'][$i];
}
Use somethings like this :
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
}
}
or
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
property.SetValue(p_object, safeValue, null);
}
}
Are you looking for
\begin{cases}
math text
\end{cases}
It wasn't very clear from the description. But may be this is what you are looking for http://en.wikipedia.org/wiki/Help:Displaying_a_formula#Continuation_and_cases
I tried all of the suggestions but was still unable to run msiexec.exe
with parameters that contained spaces. So my solution ended up using System.Diagnostics.ProcessStartInfo
:
# can have spaces here, no problems
$settings = @{
CONNECTION_STRING = "... ..."
ENTITY_CONTEXT = "... ..."
URL = "..."
}
$settingsJoined = ($settings.Keys | % { "$_=""$($settings[$_])""" }) -join " "
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.WorkingDirectory = $ScriptDirectory
$pinfo.FileName = "msiexec.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "/l* install.log /i installer.msi $settingsJoined"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
NSString *string = [NSString stringWithUTF8String:[Data bytes]];
I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.
The full shortcut target is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
So I put the following at the start of my script and it seemed to function as expected:
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
Notes: