I haven't had to do this, so take this with a grain of salt and a big helping of "test, test, test".
What happens if (in a safe controlled test environment) you directly modify the Host
column in the mysql.user
and probably mysql.db
tables? (E.g., with an update
statement.) I don't think MySQL uses the user's host as part of the password encoding (the PASSWORD
function doesn't suggest it does), but you'll have to try it to be sure. You may need to issue a FLUSH PRIVILEGES
command (or stop and restart the server).
For some storage engines (MyISAM, for instance), you may also need to check/modify the .frm
file any views that user has created. The .frm
file stores the definer, including the definer's host. (I have had to do this, when moving databases between hosts where there had been a misconfiguration causing the wrong host to be recorded...)
In SQL Server type:
Select 'Your Text'
There is no need for the FROM
or WHERE
clause.
From the Java Language Specification:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
- For type byte, the default value is zero, that is, the value of
(byte)0
.- For type short, the default value is zero, that is, the value of
(short)0
.- For type int, the default value is zero, that is,
0
.- For type long, the default value is zero, that is,
0L
.- For type float, the default value is positive zero, that is,
0.0f
.- For type double, the default value is positive zero, that is,
0.0d
.- For type char, the default value is the null character, that is,
'\u0000'
.- For type boolean, the default value is
false
.- For all reference types (§4.3), the default value is
null
.
Open the find and replace dialog (press CTRL+H).
Then select Regular expression
in the 'Search Mode' section at the bottom.
In the Find what
field enter this: [\r\n]+
In the Replace with
: ,
There is a space after the comma.
This will also replace lines like
Apples
Apricots
Pear
Avocados
Bananas
Where there are empty lines.
If your lines have trailing blank spaces you should remove those first. The simplest way to achieve this is
EDIT -> Blank Operations -> Trim Trailing Space
OR
TextFX -> TextFX Edit -> Trim trailing spaces
Be sure to set the Search Mode to "Regular expression".
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
Run the following commands to completely uninstall Jenkins from MacOS Sierra. You don't need to change anything, just run these commands.
sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins '/Library/Application Support/Jenkins' /Library/Documentation/Jenkins
sudo rm -rf /Users/Shared/Jenkins
sudo rm -rf /var/log/jenkins
sudo rm -f /etc/newsyslog.d/jenkins.conf
sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins
pkgutil --pkgs
grep 'org\.jenkins-ci\.'
xargs -n 1 sudo pkgutil --forget
Salam
Shah
I believe SET
is ANSI standard whereas the SELECT
is not. Also note the different behavior of SET
vs. SELECT
in the example below when a value is not found.
declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */
set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */
pip install pandas
works fine with pip 18.0
on macOS 10.13.6
.
In addition, to work with Xlsx files, you will need xlrd
installed.
No, you can't with pure redirection.
But with some tricks (like tee.bat) you can.
I try to explain the redirection a bit.
You redirect one of the ten streams with > file or < file
It is unimportant, if the redirection is before or after the command,
so these two lines are nearly the same.
dir > file.txt
> file.txt dir
The redirection in this example is only a shortcut for 1>, this means the stream 1 (STDOUT) will be redirected.
So you can redirect any stream with prepending the number like 2> err.txt and it is also allowed to redirect multiple streams in one line.
dir 1> files.txt 2> err.txt 3> nothing.txt
In this example the "standard output" will go into files.txt, all errors will be in err.txt and the stream3 will go into nothing.txt (DIR doesn't use the stream 3).
Stream0 is STDIN
Stream1 is STDOUT
Stream2 is STDERR
Stream3-9 are not used
But what happens if you try to redirect the same stream multiple times?
dir > files.txt > two.txt
"There can be only one", and it is always the last one!
So it is equal to dir > two.txt
Ok, there is one extra possibility, redirecting a stream to another stream.
dir 1>files.txt 2>&1
2>&1 redirects stream2 to stream1 and 1>files.txt redirects all to files.txt.
The order is important here!
dir ... 1>nul 2>&1
dir ... 2>&1 1>nul
are different. The first one redirects all (STDOUT and STDERR) to NUL,
but the second line redirects the STDOUT to NUL and STDERR to the "empty" STDOUT.
As one conclusion, it is obvious why the examples of Otávio Décio and andynormancx can't work.
command > file >&1
dir > file.txt >&2
Both try to redirect stream1 two times, but "There can be only one", and it's always the last one.
So you get
command 1>&1
dir 1>&2
And in the first sample redirecting of stream1 to stream1 is not allowed (and not very useful).
Hope it helps.
Had a similar issue while installing "Lua" in OS X using homebrew. I guess it could be useful for other users facing similar issue in homebrew.
On running the command:
$ brew install lua
The command returned an error:
Error: /usr/local/opt/lua is not a valid keg
(in general the error can be of /usr/local/opt/ is not a valid keg
FIXED it by deleting the file/directory it is referring to, i.e., deleting the "/usr/local/opt/lua" file.
root-user # rm -rf /usr/local/opt/lua
And then running the brew install command returned success.
Add @JsonInclude(JsonInclude.Include.NON_NULL)
(forces Jackson to serialize null values) to the class as well as @JsonIgnore
to the password field.
You could of course set @JsonIgnore
on createdBy and updatedBy as well if you always want to ignore then and not just in this specific case.
UPDATE
In the event that you do not want to add the annotation to the POJO itself, a great option is Jackson's Mixin Annotations. Check out the documentation
Use the Javascript string split() function.
var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');
// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc
For some kind of reason my NULL values where of data length 8. That is why none of the abovementioned seemed to work. If you encounter the same problem, use the following code:
--Check the length of your NULL values
SELECT DATALENGTH(COLUMN) as length_column
FROM your_table
--Filter the length of your NULL values (8 is used as example)
WHERE DATALENGTH(COLUMN) > 8
Teylyn's answer worked great for me, but I had to modify it a bit to get proper results. I want to provide an extended explanation for whoever would need it.
My setup was as follows:
I put the following formula in cell A1 of Sheet3:
=iferror(vlookup(Sheet1!A$1;Sheet2!$A$1:$D$50;column(A1);false);Sheet1!A1)
Read this as follows: Take the value of the first column in Sheet1 (old data). Look up in Sheet2 (updated rows). If present, output the value from the indicated column in Sheet2. On error, output the value for the current column of Sheet1.
Notes:
In my version of the formula, ";" is used as parameter separator instead of ",". That is because I am located in Europe and we use the "," as decimal separator. Change ";" back to "," if you live in a country where "." is the decimal separator.
A$1: means always take column 1 when copying the formula to a cell in a different column. $A$1 means: always take the exact cell A1, even when copying the formula to a different row or column.
After pasting the formula in A1, I extended the range to columns B, C, etc., until the full width of my table was reached. Because of the $-signs used, this gives the following formula's in cells B1, C1, etc.:
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(B1);FALSE);'Sheet1'!B1)
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(C1);FALSE);'Sheet1'!C1)
and so forth. Note that the lookup is still done in the first column. This is because VLOOKUP needs the lookup data to be sorted on the column where the lookup is done. The output column is however the column where the formula is pasted.
Next, select a rectangle in Sheet 3 starting at A1 and having the size of the data in Sheet1 (same number of rows and columns). Press Ctrl-D to copy the formulas of the first row to all selected cells.
Cells A2, A3, etc. will get these formulas:
=IFERROR(VLOOKUP('Sheet1'!$A2;'Sheet2'!$A$1:$D$50;COLUMN(A2);FALSE);'Sheet1'!A2)
=IFERROR(VLOOKUP('Sheet1'!$A3;'Sheet2'!$A$1:$D$50;COLUMN(A3);FALSE);'Sheet1'!A3)
Because of the use of $-signs, the lookup area is constant, but input data is used from the current row.
It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?
But look at this, a well-formed XML document:
<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>
The root of this document has three children: a processing instruction, a comment, and an element.
So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:
<xsl:template match="/comment()"/>
Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*
.
Use the location header flag:
curl -L <URL>
Free read-only viewers:
tail
." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.Free editors:
Builtin programs (no installation required):
MORE
, not the Unix more
. A console program that allows you to view a file, one screen at a time.Web viewers:
Paid editors:
Just as a regular SELECT
?
SELECT
Val1, Val2, Val3,
Total = Val1 + Val2 + Val3
FROM dbo.Emp
Or do you want to determine that total and update the table with those values?
UPDATE dbo.Emp
SET Total = Val1 + Val2 + Val3
If you want to have this total be current at all times - you should have a computed column in your table:
ALTER TABLE dbo.Emp
ADD CurrentTotal AS Val1 + Val2 + Val3 PERSISTED
Then you will always get the current total - even if the values change:
SELECT
Val1, Val2, Val3, CurrentTotal
FROM dbo.Emp
Don't forget about spaces:
source=""
samples=("")
if [ $1 = "country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi
It selects all elements where the class name contains the string "span"
somewhere. There's also ^=
for the beginning of a string, and $=
for the end of a string. Here's a good reference for some CSS selectors.
I'm only familiar with the bootstrap classes spanX
where X is an integer, but if there were other selectors that ended in span
, it would also fall under these rules.
It just helps to apply blanket CSS rules.
Trying ?max
, you'll see that it actually has a na.rm =
argument, set by default to FALSE
. (That's the common default for many other R functions, including sum()
, mean()
, etc.)
Setting na.rm=TRUE
does just what you're asking for:
d <- c(1, 100, NA, 10)
max(d, na.rm=TRUE)
If you do want to remove all of the NA
s, use this idiom instead:
d <- d[!is.na(d)]
A final note: Other functions (e.g. table()
, lm()
, and sort()
) have NA
-related arguments that use different names (and offer different options). So if NA
's cause you problems in a function call, it's worth checking for a built-in solution among the function's arguments. I've found there's usually one already there.
The problem is that the base class foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
just to extend @GabLeRoux's answer:
[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)
this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.
PostgreSql is very advanced when related to logging techniques
Logs are stored in Installationfolder/data/pg_log folder
. While log settings are placed in postgresql.conf
file.
Log format is usually set as stderr
. But CSV log format is recommended. In order to enable CSV format change in
log_destination = 'stderr,csvlog'
logging_collector = on
In order to log all queries, very usefull for new installations, set min. execution time for a query
log_min_duration_statement = 0
In order to view active Queries on your database, use
SELECT * FROM pg_stat_activity
To log specific queries set query type
log_statement = 'all' # none, ddl, mod, all
For more information on Logging queries see PostgreSql Log.
I always liked going after it directly:
SELECT
DB_NAME( dbid ) AS DatabaseName,
CAST( ( SUM( size ) * 8 ) / ( 1024.0 * 1024.0 ) AS decimal( 10, 2 ) ) AS DbSizeGb
FROM
sys.sysaltfiles
GROUP BY
DB_NAME( dbid )
Is this code snippet work for you?
if (!count($_SESSION)>0) {
session_start();
}
ASP.NET MVC 5 solutions:
App_Start/FilterConfig.cs
's RegisterGlobalFilters
method: public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// ...
filters.Add(new OutputCacheAttribute
{
NoStore = true,
Duration = 0,
VaryByParam = "*",
Location = System.Web.UI.OutputCacheLocation.None
});
}
}
OutputCache
directive at Controller
or View
level. For regular Controller it's[OutputCache(NoStore = true, Duration = 0, Location=System.Web.UI.ResponseCacheLocation.None, VaryByParam = "*")]
or if it's an ApiController
it'd be
[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, Location = System.Web.UI.OutputCacheLocation.None, VaryByParam = "*")]
I copied the Java.exe from
C:\Windows\System32
to
C:\Windows\SysWOW64
and it worked.
I'm using 64 bit Windows 8.
You can use the following extension method from any web page or nested user control:
static class Extensions
{
public static void ShowAlert(this Control control, string message)
{
if (!control.Page.ClientScript.IsClientScriptBlockRegistered("PopupScript"))
{
var script = String.Format("<script type='text/javascript' language='javascript'>alert('{0}')</script>", message);
control.Page.ClientScript.RegisterClientScriptBlock(control.Page.GetType(), "PopupScript", script);
}
}
}
like this:
class YourPage : Page
{
private void YourMethod()
{
try
{
// do stuff
}
catch(Exception ex)
{
this.ShowAlert(ex.Message);
}
}
}
The main reason for the error is that the default encoding assumed by python is ASCII.
Hence, if the string data to be encoded by encode('utf8')
contains character that is outside of ASCII range e.g. for a string like 'hgvcj???387', python would throw error because the string is not in the expected encoding format.
If you are using python version earlier than version 3.5, a reliable fix would be to set the default encoding assumed by python to utf8
:
import sys
reload(sys)
sys.setdefaultencoding('utf8')
name = school_name.encode('utf8')
This way python would be able to anticipate characters within a string that fall outside of ASCII range.
However, if you are using python version 3.5 or above, reload() function is not available, so you would have to fix it using decode e.g.
name = school_name.decode('utf8').encode('utf8')
Advice for R
newcomers like me : beware, the following is a list of a single object :
> mylist <- list (1:10)
> length (mylist)
[1] 1
In such a case you are not looking for the length of the list, but of its first element :
> length (mylist[[1]])
[1] 10
This is a "true" list :
> mylist <- list(1:10, rnorm(25), letters[1:3])
> length (mylist)
[1] 3
Also, it seems that R
considers a data.frame as a list :
> df <- data.frame (matrix(0, ncol = 30, nrow = 2))
> typeof (df)
[1] "list"
In such a case you may be interested in ncol()
and nrow()
rather than length()
:
> ncol (df)
[1] 30
> nrow (df)
[1] 2
Though length()
will also work (but it's a trick when your data.frame has only one column) :
> length (df)
[1] 30
> length (df[[1]])
[1] 2
How about:
import copy
d = { ... }
d2 = copy.deepcopy(d)
Python 2 or 3:
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>> my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> my_copy = copy.deepcopy(my_dict)
>>> my_dict['a'][2] = 7
>>> my_copy['a'][2]
3
>>>
Reasons of ignoring these argument is permanent generation has been removed in HotSpot for JDK8 because of following drawbacks
The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace. The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error.
Advantages of MetaSpace
Metaspace Tuning
The maximum metaspace size can be set using the -XX:MaxMetaspaceSize flag, and the default is unlimited, which means that only your system memory is the limit. The -XX:MetaspaceSize tuning flag defines the initial size of metaspace If you don’t specify this flag, the Metaspace will dynamically re-size depending of the application demand at runtime.
Change enables other optimizations and features in the future
There is improved GC performace also.
Or you can try to access the columns directly by name:
while(dr.Read())
{
string col1 = (string)dr["Value1"];
string col2 = (string)dr["Value2"];
string col3 = (string)dr["Value3"];
}
This can also help you by showing full details of the error on a client's browser.
<system.web>
<customErrors mode="Off"/>
</system.web>
<system.webServer>
<httpErrors errorMode="Detailed" />
</system.webServer>
It should be like
params.permit(:id => [])
Also since rails version 4+ you can use:
params.permit(id: [])
In a simpler way open search window and search for connection.xml
gives a right click on that file and select open file/folder location.
Once you get that connection.xml
try to import it into SQLDeveloper by right clicking to CONNECTIONS.
Adding on to the main response that recommends the usage of WpfAnimatedGif, you must add the following lines in the end if you are swapping an image with a Gif to ensure the animation actually executes:
ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));
ImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);
So your code will look like:
var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fileName);
image.EndInit();
ImageBehavior.SetAnimatedSource(img, image);
ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));
ImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);
You have to catch the SIGINT signal (we are talking POSIX right?)
See @Gab Royer´s answer for sigaction.
Example:
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
void my_handler(sig_t s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
signal (SIGINT,my_handler);
while(1);
return 0;
}
Also, if you're using C++, you can just create a function like this:
string prd(const double x, const int decDigits) {
stringstream ss;
ss << fixed;
ss.precision(decDigits); // set # places after decimal
ss << x;
return ss.str();
}
You can then output any double myDouble
with n
places after the decimal point with code such as this:
std::cout << prd(myDouble,n);
Since an ounce of experience is worth a ton of theory, I tried a little test program for MULTILINE
:
#define MULTILINE(...) #__VA_ARGS__
const char *mstr[] =
{
MULTILINE(1, 2, 3), // "1, 2, 3"
MULTILINE(1,2,3), // "1,2,3"
MULTILINE(1 , 2 , 3), // "1 , 2 , 3"
MULTILINE( 1 , 2 , 3 ), // "1 , 2 , 3"
MULTILINE((1, 2, 3)), // "(1, 2, 3)"
MULTILINE(1
2
3), // "1 2 3"
MULTILINE(1\n2\n3\n), // "1\n2\n3\n"
MULTILINE(1\n
2\n
3\n), // "1\n 2\n 3\n"
MULTILINE(1, "2" \3) // "1, \"2\" \3"
};
Compile this fragment with cpp -P -std=c++11 filename
to reproduce.
The trick behind #__VA_ARGS__
is that __VA_ARGS__
does not process the comma separator. So you can pass it to the stringizing operator. Leading and trailing spaces are trimmed, and spaces (including newlines) between words are compressed to a single space then. Parentheses need to be balanced. I think these shortcomings explain why the designers of C++11, despite #__VA_ARGS__
, saw the need for raw string literals.
With Java 9, we get access to jshell
, so one can write something like this:
import jdk.jshell.JShell;
import java.lang.StringBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Eval {
public static void main(String[] args) throws IOException {
try(JShell js = JShell.create(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
js.onSnippetEvent(snip -> {
if (snip.status() == jdk.jshell.Snippet.Status.VALID) {
System.out.println("? " + snip.value());
}
});
System.out.print("> ");
for (String line = br.readLine(); line != null; line = br.readLine()) {
js.eval(js.sourceCodeAnalysis().analyzeCompletion(line).source());
System.out.print("> ");
}
}
}
}
Sample run:
> 1 + 2 / 4 * 3
? 1
> 32 * 121
? 3872
> 4 * 5
? 20
> 121 * 51
? 6171
>
Slightly op, but that's what Java currently has to offer
This tutorial gives a simple, yet elegant, solution, which i transcribe:
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
...
std::string my_val = stringify(val);
days
, years
, etc., are part of Active Support, So this won't work in irb
, but it should work in rails console
.
Using code::blocks , I have solved this error by doing :
workspace properties > build target > build target files
and checking every project file.
Use config.to_prepare to load you monkey patches/extensions for every request in development mode.
config.to_prepare do |action_dispatcher|
# More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
Rails.logger.info "\n--- Loading extensions for #{self.class} "
Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
Rails.logger.info "Loading extension(s): #{entry}"
require_dependency "#{entry}"
end
Rails.logger.info "--- Loaded extensions for #{self.class}\n"
end
The solution above was not working for me. I had to set 'class count to use import with '*'' to a high value, e.g. 999.
Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium
Try this
padding:8px;
overflow: hidden;
zoom: 1;
text-align: left;
font-size: 13px;
font-family: "Trebuchet MS",Arial,Sans;
line-height: 24px;
color: black;
border-bottom: solid 1px #BBB;
background:url('images/checked.gif') white no-repeat;
This is full css.. Why you use padding:0 8px
, then override it with paddings? This is what you need...
There are two options depending what you want to achieve :
You can use the hidden directive to show or hide an element
<div [hidden]="!edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
You can use the ngIf control directive to add or remove the element. This is different of the hidden directive because it does not show / hide the element, but it add / remove from the DOM. You can loose unsaved data of the element. It can be the better choice for an edit component that is cancelled.
<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
For you problem of change after 3 seconds, it can be due to incompatibility with setTimeout. Did you include angular2-polyfills.js library in your page ?
After the docker installation you have 3 networks by default:
docker network ls
NETWORK ID NAME DRIVER SCOPE
f3be8b1ef7ce bridge bridge local
fbff927877c1 host host local
023bb5940080 none null local
I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.
$ docker run -d jenkins
1498e581cdba jenkins "/bin/tini -- /usr..." 3 minutes ago Up 3 minutes 8080/tcp, 50000/tcp friendly_bell
In the dockerfile of jenkins the ports 8080
and 50000
are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080
and 50000
. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16",
If you want to access them from the outside you have to map the ports with -p 8080:8080
. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080
will route to your bridgenetwork on port 8080
.
Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1efd834949b2 jenkins "/bin/tini -- /usr..." 6 minutes ago Up 6 minutes eloquent_panini
1498e581cdba jenkins "/bin/tini -- /usr..." 10 minutes ago Up 10 minutes 8080/tcp, 50000/tcp friendly_bell
The difference is with the ports. Your container is now inside your host network. So if you open port 8080
on your host you will acces the container immediately.
$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT
I've opened port 8080
in my firewall and when I'm now accesing my server on port 8080
I'm accessing my jenkins. I think this blog is also useful to understand it better.
ps -ax | grep mysql
*stop and kill any MySQL processes
brew remove mysql
brew cleanup
sudo rm /usr/local/mysql
sudo rm -rf /usr/local/var/mysql
sudo rm -rf /usr/local/mysql*
sudo rm ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
sudo rm -rf /Library/StartupItems/MySQLCOM
sudo rm -rf /Library/PreferencePanes/MySql*
launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
edit /etc/hostconfig
and remove the line MYSQLCOM=-YES-
rm -rf ~/Library/PreferencePanes/My*
sudo rm -rf /Library/Receipts/mysql*
sudo rm -rf /Library/Receipts/MySQL*
sudo rm -rf /private/var/db/receipts/*mysql*
*restart your computer just to ensure any MySQL processes are killed try to run mysql, it shouldn't work
I believe that dropping the size of the image down to an almost icon size, say 48x48, then converting to greyscale, then taking the difference between pixels, or Delta, should work well. Because we're comparing the change in pixel color, rather than the actual pixel color, it won't matter if the image is slightly lighter or darker. Large changes will matter since pixels getting too light/dark will be lost. You can apply this across one row, or as many as you like to increase the accuracy. At most you'd have 47x47=2,209 subtractions to make in order to form a comparable Key.
If you want to search on both FROM and TO airports, you'll want to join on the Airports table twice - then you can use both from and to tables in your results set:
SELECT
Flights.*,fromAirports.*,toAirports.*
FROM
Flights
INNER JOIN
Airports fromAirports on Flights.fairport = fromAirports.code
INNER JOIN
Airports toAirports on Flights.tairport = toAirports.code
WHERE
...
We can achieve this using a recursive loop
public static int digitCount(int numberInput, int i) {
while (numberInput > 0) {
i++;
numberInput = numberInput / 10;
digitCount(numberInput, i);
}
return i;
}
public static void printString() {
int numberInput = 1234567;
int digitCount = digitCount(numberInput, 0);
System.out.println("Count of digit in ["+numberInput+"] is ["+digitCount+"]");
}
Move path\to\anaconda
in the PATH above path\to\python
Make sure you've got this in /etc/nginx/fastcgi_params
fastcgi_param SCRIPT_FILENAME $request_filename;
Who knows why this isn't there already? The amount of time this must collectively waste!
http://www.php.net/mysql_query says "mysql_query()
returns a resource".
http://www.php.net/json_encode says it can encode any value "except a resource".
You need to iterate through and collect the database results in an array, then json_encode
the array.
The date can be converted in typescript to this format 'yyyy-MM-dd'
by using Datepipe
import { DatePipe } from '@angular/common'
...
constructor(public datepipe: DatePipe){}
...
myFunction(){
this.date=new Date();
let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd');
}
and just add Datepipe in 'providers' array of app.module.ts. Like this:
import { DatePipe } from '@angular/common'
...
providers: [DatePipe]
One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get
public class PageViewModel : IHandle<SomeMessage>
{
...
public async void Handle(SomeMessage message)
{
ShowLoadingAnimation();
// makes UI very laggy, but still not dead
await this.contentLoader.LoadContentAsync();
HideLoadingAnimation();
}
}
public class ContentLoader
{
public async Task LoadContentAsync()
{
var tasks = new List<Task>();
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoIoBoundWorkAsync());
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoSomeOtherWorkAsync());
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
First, it's always worth noting that git reset --hard
is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status
is clean (that is, empty) before using it.
Initially you say the following:
So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:
That's incorrect. Git only records the state of the files when you stage them (with git add
) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add
to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)
In your question you then go on to ask the following:
When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro
How do I then revert the files on my hard drive back to that previous commit?
If you do git reset --hard <SOME-COMMIT>
then Git will:
master
) back to point at <SOME-COMMIT>
.<SOME-COMMIT>
.HEAD
points to your current branch (or current commit), so all that git reset --hard HEAD
will do is to throw away any uncommitted changes you have.
So, suppose the good commit that you want to go back to is f414f31
. (You can find that via git log
or any history browser.) You then have a few different options depending on exactly what you want to do:
git reset --hard f414f31
. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31
will no longer be in the history of your master
branch.Create a new commit that represents exactly the same state of the project as f414f31
, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:
git reset --hard f414f31
git reset --soft HEAD@{1}
git commit -m "Reverting to the state of the project at f414f31"
import yaml
data = dict(
A = 'a',
B = dict(
C = 'c',
D = 'd',
E = 'e',
)
)
with open('data.yml', 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
The default_flow_style=False
parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:
A: a
B: {C: c, D: d, E: e}
In the manual for GNU make, they talk about this specific example when describing the value
function:
The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.
The syntax of the value function is:
$(value variable)
Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)
The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:
FOO = $PATH all: @echo $(FOO) @echo $(value FOO)
The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.
Actually… there is! Sort of. box-shadow
defaults to color
, just like border
does.
According to http://dev.w3.org/.../#the-box-shadow
The color is the color of the shadow. If the color is absent, the used color is taken from the ‘color’ property.
In practice, you have to change the color
property and leave box-shadow
without a color:
box-shadow: 1px 2px 3px;
color: #a00;
box-shadow
at all) div {_x000D_
box-shadow: 0 0 50px;_x000D_
transition: 0.3s color;_x000D_
}_x000D_
.green {_x000D_
color: green;_x000D_
}_x000D_
.red {_x000D_
color: red;_x000D_
}_x000D_
div:hover {_x000D_
color: yellow;_x000D_
}_x000D_
_x000D_
/*demo style*/_x000D_
body {_x000D_
text-align: center;_x000D_
}_x000D_
div {_x000D_
display: inline-block;_x000D_
background: white;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
margin: 30px;_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<div class="green"></div>_x000D_
<div class="red"></div>
_x000D_
The bug mentioned in the comment below has since been fixed :)
Give a class for eg: scroll
to the textarea tag. And in the css add this property -
.scroll::-webkit-scrollbar {
display: none;
}
_x000D_
<textarea class='scroll'></textarea>
_x000D_
It worked for without missing the scroll part
Well, this is my final solution for a simple db, for Linux:
# Read this before!
#
# * roles in postgres are users, and can be used also as group of users
# * $ROLE_LOCAL will be the user that access the db for maintenance and
# administration. $ROLE_REMOTE will be the user that access the db from the webapp
# * you have to change '$ROLE_LOCAL', '$ROLE_REMOTE' and '$DB'
# strings with your desired names
# * it's preferable that $ROLE_LOCAL == $DB
#-------------------------------------------------------------------------------
//----------- SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - START ----------//
cd /etc/postgresql/$VERSION/main
sudo cp pg_hba.conf pg_hba.conf_bak
sudo -e pg_hba.conf
# change all `md5` with `scram-sha-256`
# save and exit
//------------ SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - END -----------//
sudo -u postgres psql
# in psql:
create role $ROLE_LOCAL login createdb;
\password $ROLE_LOCAL
create role $ROLE_REMOTE login;
\password $ROLE_REMOTE
create database $DB owner $ROLE_LOCAL encoding "utf8";
\connect $DB $ROLE_LOCAL
# Create all tables and objects, and after that:
\connect $DB postgres
revoke connect on database $DB from public;
revoke all on schema public from public;
revoke all on all tables in schema public from public;
grant connect on database $DB to $ROLE_LOCAL;
grant all on schema public to $ROLE_LOCAL;
grant all on all tables in schema public to $ROLE_LOCAL;
grant all on all sequences in schema public to $ROLE_LOCAL;
grant all on all functions in schema public to $ROLE_LOCAL;
grant connect on database $DB to $ROLE_REMOTE;
grant usage on schema public to $ROLE_REMOTE;
grant select, insert, update, delete on all tables in schema public to $ROLE_REMOTE;
grant usage, select on all sequences in schema public to $ROLE_REMOTE;
grant execute on all functions in schema public to $ROLE_REMOTE;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on tables to $ROLE_LOCAL;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on sequences to $ROLE_LOCAL;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on functions to $ROLE_LOCAL;
alter default privileges for role $ROLE_REMOTE in schema public
grant select, insert, update, delete on tables to $ROLE_REMOTE;
alter default privileges for role $ROLE_REMOTE in schema public
grant usage, select on sequences to $ROLE_REMOTE;
alter default privileges for role $ROLE_REMOTE in schema public
grant execute on functions to $ROLE_REMOTE;
# CTRL+D
Make sure that the path actually leads to the executables. I'm using version 11 and it did not work until this was set as the path:
C:\Program Files\PostgreSQL\11\bin\bin
Maybe this is how version 11 is structured or I somehow botched the installation but I haven't had a problem since.
I want to select the text of a string that is located after the occurrence of substring
You could use:
substring-after($string,$match)
If you want a subtring of the above with some length then use:
substring(substring-after($string,$match),1,$length)
But problems begin if there is no ocurrence of the matching substring... So, if you want a substring with specific length located after the occurrence of a substring, or from the whole string if there is no match, you could use:
substring(substring-after($string,substring-before($string,$match)),
string-length($match) * contains($string,$match) + 1,
$length)
This answer is out of date and shouldn't be used.
1) Average latency is much faster on mobile in 2017. https://opensignal.com/reports/2016/02/usa/state-of-the-mobile-network
2) HTTP2 multiplexes https://http2.github.io/faq/#why-is-http2-multiplexed
"Data URIs" should definitely be considered for mobile sites. HTTP access over cellular networks comes with higher latency per request/response. So there are some use cases where jamming your images as data into CSS or HTML templates could be beneficial on mobile web apps. You should measure usage on a case-by-case basis -- I'm not advocating that data URIs should be used everywhere in a mobile web app.
Note that mobile browsers have limitations on total size of files that can be cached. Limits for iOS 3.2 were pretty low (25K per file), but are getting larger (100K) for newer versions of Mobile Safari. So be sure to keep an eye on your total file size when including data URIs.
http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/
Just grep through the working directory and send the output through the xargs command:
grep -lr '<<<<<<<' . | xargs git checkout --ours
or
grep -lr '<<<<<<<' . | xargs git checkout --theirs
How this works: grep
will search through every file in the current directory (the .
) and subdirectories recursively (the -r
flag) looking for conflict markers (the string '<<<<<<<')
the -l
or --files-with-matches
flag causes grep to output only the filename where the string was found. Scanning stops after first match, so each matched file is only output once.
The matched file names are then piped to xargs, a utility that breaks up the piped input stream into individual arguments for git checkout --ours
or --theirs
More at this link.
Since it would be very inconvenient to have to type this every time at the command line, if you do find yourself using it a lot, it might not be a bad idea to create an alias for your shell of choice: Bash is the usual one.
This method should work through at least Git versions 2.4.x
Invoking of validation on form element could be handled by triggering change event on this element:
a) exemple: trigger change on separated element in form
$scope.formName.elementName.$$element.change();
b) exemple: trigger change event for each of form elements for example on ng-submit, ng-click, ng-blur ...
vm.triggerChangeForFormElements = function() {
// trigger change event for each of form elements
angular.forEach($scope.formName, function (element, name) {
if (!name.startsWith('$')) {
element.$$element.change();
}
});
};
c) and one more way for that
var handdleChange = function(form){
var formFields = angular.element(form)[0].$$controls;
angular.forEach(formFields, function(field){
field.$$element.change();
});
};
The -H 'Cache-Control: no-cache'
argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.
curl "http://www.example.com?foo123"
You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s
, which will return the seconds since epoch.
curl "http://www.example.com?$(date +%s)"
No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.
XML has only one definition for a comment:
'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
XML forbids --
in comments to maintain compatibility with SGML.
This means a class is redundantly mentioned with a class function. Try removing JSONDeserializer::
Assuming:
<input type="file" name="file1" id="theFile">
The JavaScript would be:
var fileName = document.getElementById('theFile').files[0].name;
You might be needing a cleanup:
git gc --prune=now
or you might be needing a prune:
git remote prune public
prune
Deletes all stale tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".
With --dry-run option, report what branches will be pruned, but do no actually prune them.
However, it appears these should have been cleaned up earlier with
git remote rm public
rm
Remove the remote named <name>. All remote tracking branches and configuration settings for the remote are removed.
So it might be you hand-edited your config file and this did not occur, or you have privilege problems.
Maybe run that again and see what happens.
If you take a look in the revision logs, you'll note I suggested more "correct" techniques, which for whatever reason didn't want to work on their repository.
I suspected the OP had done something that left their tree in an inconsistent state that caused it to behave a bit strangely, and git gc
was required to fix up the left behind cruft.
Usually git branch -rd origin/badbranch
is sufficient for nuking a local tracking branch , or git push origin :badbranch
for nuking a remote branch, and usually you will never need to call git gc
Compound checking:
if (thing.foo && thing.foo.bar) {
... thing.foor.bar exists;
}
Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm
Mathcha is a sophisticated mathematics editor, but it can be used to render individual equations and save them as pure html, which you can then add to your documents as inline html OR you can save as SVG and insert as an image. https://www.mathcha.io/
Try this if you unbind the onclick event by ID Then use:
$('#youLinkID').attr('onclick','').unbind('click');
Try this if you unbind the onclick event by Class Then use:
$('.className').attr('onclick','').unbind('click');
I just figured out how to do this:
It appears that when you add a parent folder to version control, Eclipse adds all sub-folders. Once the sub-folders are added to version control, it is not possible to ignore them.
Here's how to do it:
Right click on the top level folder and add to version control Right click on the child folder you want to ignore, revert Right click on the child folder you want to ignore, svn:ignore (which will now be available)
Although Google uses BigTable for all their main applications, they also use MySQL for other (perhaps minor) apps.
Escape the apostrophe in O'Neal
by writing O''Neal
(two apostrophes).
In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).
You can manually trigger the garbage collection using
import gc
gc.collect()
But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.
If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.
We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.
l = ["a", "b", "c", "d", "e"]
To create a dictionary we can use the built in dict
function for Mapping Types as per the manual the following methods are supported.
dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])
The last option suggests that we supply a list of lists with 2 values or (key, value)
tuples, so we want to turn our sequential list into:
l = [["a", "b"], ["c", "d"], ["e",]]
We are also introduced to the zip
function, one of the built-in functions which the manual explains:
returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments
In other words if we can turn our list into two lists a, c, e
and b, d
then zip
will do the rest.
Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:
>>> l[::2]
['a', 'c', 'e']
>>> l[1::2]
['b', 'd']
>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]
>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}
Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:
>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]
>>> b is a
True
>>> b = a[:]
>>> b
[1, 2, 3]
>>> b is a
False
Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.
Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.
Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.
*[iter(l)]*2
Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.
>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']
>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]
>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]
>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]
>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]
>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}
As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.
You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.
>>> it = iter(l)
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}
What about the empty key e
if you've noticed it has been missing from all the examples which is because zip
picks the shortest of the two arguments, so what are we to do.
Well one solution might be adding an empty value to odd length lists, you may choose to use append
and an if
statement which would do the trick, albeit slightly boring, right?
>>> if len(l) % 2:
... l.append("")
>>> l
['a', 'b', 'c', 'd', 'e', '']
>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}
Now before you shrug away to go type from itertools import izip_longest
you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.
I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None
empty value when required, automagically.
>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']
>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None}
Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.
$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real 0m3.755s
user 0m2.815s
sys 0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real 0m2.102s
user 0m1.451s
sys 0m0.539s
However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.
$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real 0m0.046s
user 0m0.029s
sys 0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real 0m0.067s
user 0m0.042s
sys 0m0.021s
$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real 0m0.074s
user 0m0.050s
sys 0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real 0m0.075s
user 0m0.047s
sys 0m0.024s
See nothing to it! =)
nJoy!
You can try the following code to convert the image to hex string
<?php
$image = 'sample.bmp';
$file = fopen($image, 'r') or die("Could not open $image");
while ($file && !feof($file)){
$chunk = fread($file, 1000000); # You can affect performance altering
this number. YMMV.
# This loop will be dog-slow, almost for sure...
# You could snag two or three bytes and shift/add them,
# but at 4 bytes, you violate the 7fffffff limit of dechex...
# You could maybe write a better dechex that would accept multiple bytes
# and use substr... Maybe.
for ($byte = 0; $byte < strlen($chunk); $byte++)){
echo dechex(ord($chunk[$byte]));
}
}
?>
I think it's best if you use methods with generic arguments, like the following :
public static void SerializeToXml<T>(T obj, string fileName)
{
using (var fileStream = new FileStream(fileName, FileMode.Create))
{
var ser = new XmlSerializer(typeof(T));
ser.Serialize(fileStream, obj);
}
}
public static T DeserializeFromXml<T>(string xml)
{
T result;
var ser = new XmlSerializer(typeof(T));
using (var tr = new StringReader(xml))
{
result = (T)ser.Deserialize(tr);
}
return result;
}
Or better
window.location.assign("relative or absolute address");
that tends to work best across all browsers and mobile
$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
'body' => json_encode($dataArray)
]);
$response = $request->getBody();
Add
openssl.cafile
in php.ini
file
Go to c:/wamp/apps/phpadmin3.5.2 Make a new subfolder called ‘upload’ Edit config.inc.php to find and update this line: $cfg[‘UploadDir’] = ‘upload’ Now when you import a database, you will give a drop-down list in web server upload directory with all the files in this directory. Chose the file you want and you are done.
The C++ string class is std::string
. To use it you need to include the <string>
header.
For the fundamentals of how to use std::string
, you'll want to consult a good introductory C++ book.
var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);
The included utility that installs to /usr/local/bin/charm
did not work for me on OS X, so I hacked together this utility instead. It actually works!
#!/usr/bin/env bash
if [ -z "$1" ]
then
echo ""
echo "Usage: charm <filename>"
exit
fi
FILENAME=$1
function myreadlink() {
(
cd $(dirname $1) # or cd ${1%/*}
echo $PWD/$(basename $1) # or echo $PWD/${1##*/}
)
}
FULL_FILE=`myreadlink $FILENAME`;
/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm $FULL_FILE
Adding to Brian Agnew's answer.
You can also do //div[@id='..' or @class='...]
and you can have parenthesized expressions inside //div[@id='..' and (@class='a' or @class='b')]
.
It's not a direct answer on question (its not about Actions
), but it also allow you to scroll easily to required element:
element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view
This actually intend to return you coordinates (x
, y
) of element on page, but also scroll down right to target element
This works perfectly and this is official html5.
<object data="https://link-to-pdf"></object>
You can also name columns directly in the cbind
call, e.g.
cbind(date=c(0,1), high=c(2,3))
Output:
date high
[1,] 0 2
[2,] 1 3
<select name="xx" class="xxx" onchange="_name(this.options[this.selectedIndex].value,this.options[this.selectedIndex].getAttribute('rel'))">
<option value="x" rel="xy">aa</option>
<option value="xxx" rel="xyy">bb</option>
</select>
//for javascript
function _name(value,rel) {
alert(value+"-"+rel);
}
Try this:
return Redirect("http://www.website.com");
$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);
Note: only work for your example.
For red lines an points
plt.plot(dates, values, '.r-')
or for x markers and blue lines
plt.plot(dates, values, 'xb-')
use ng-bind-html-unsafe
it will apply html with text inside like below:
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
{{ opt.text }}
</li>
I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.
Basically, when you have something like:
<form onsubmit="return callSomeFunction();"></form>
or
<a href="#" onclick="return callSomeFunction();"></a>`
and callSomeFunction()
returns true, then the form
or a
will submit, otherwise it won't.
Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.
I was looking at this post to find the answer but... I think everyone on this post was facing the same scenario as me: scrollToPosition()
was fully ignored, for an evident reason.
What I was using?
recyclerView.scrollToPosition(items.size());
... what WORKED?
recyclerView.scrollToPosition(items.size() - 1);
For applications such as Squirrel SQL Client (http://squirrel-sql.sourceforge.net/) version 4 you can set "serverTimezone" under "driver properties" to GMT+1
(example of timezone "Europe/Vienna).
Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.
I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.
Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.
when you declare int array[2]; you reserve 2 memory spaces of 4 bytes each(32bit program). if you type array[4] in your code it still corresponds to a valid call but only at run time will it throw an unhandled exception. C++ uses manual memory management. This is actually a security flaw that was used for hacking programs
this can help understanding:
int * somepointer;
somepointer[0]=somepointer[5];
At first simply uninstall wifi drivers and softwares just keep wifi drivers + from device manager....network adapters...remove all virtual connections
then
Press the Windows + R key combination to bring up a run box, type ncpa.cpl and hit enter.
netsh wlan set hostednetwork mode=allow ssid=”How-To Geek” key=”Pa$$w0rd”
netsh wlan start hostednetwork
netsh wlan show hostednetwork
its working for me and on others PC.
There is a specific example that "_" be used:
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
may be equal to :
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix
Applying “_” in some scenarios will automatically convert to “(x$n) => x$n ”
As @nasreddine answered or you can use /d
cd /d d:\Docs\Java
For more help on the cd
command use:
C:\Documents and Settings\kenny>help cd
Displays the name of or changes the current directory.
CHDIR [/D] [drive:][path] CHDIR [..] CD [/D] [drive:][path] CD [..]
.. Specifies that you want to change to the parent directory.
Type CD drive: to display the current directory in the specified drive. Type CD without parameters to display the current drive and directory.
Use the /D switch to change current drive in addition to changing current directory for a drive.
If Command Extensions are enabled CHDIR changes as follows:
The current directory string is converted to use the same case as the on disk names. So CD C:\TEMP would actually set the current directory to C:\Temp if that is the case on disk.
CHDIR command does not treat spaces as delimiters, so it is possible to CD into a subdirectory name that contains a space without surrounding the name with quotes. For example:
cd \winnt\profiles\username\programs\start menu
is the same as:
cd "\winnt\profiles\username\programs\start menu"
which is what you would have to type if extensions were disabled.
I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY
(scrollWidth/Height - clientWidth/Height) is a good indicator for the presence of a scrollbar, but it will give you a "false positive" answer on many occasions. if you need to be accurate i would suggest using the following function. instead of trying to guess if the element is scrollable - you can scroll it...
function isScrollable( el ){_x000D_
var y1 = el.scrollTop;_x000D_
el.scrollTop += 1;_x000D_
var y2 = el.scrollTop;_x000D_
el.scrollTop -= 1;_x000D_
var y3 = el.scrollTop;_x000D_
el.scrollTop = y1;_x000D_
var x1 = el.scrollLeft;_x000D_
el.scrollLeft += 1;_x000D_
var x2 = el.scrollLeft;_x000D_
el.scrollLeft -= 1;_x000D_
var x3 = el.scrollLeft;_x000D_
el.scrollLeft = x1;_x000D_
return {_x000D_
horizontallyScrollable: x1 !== x2 || x2 !== x3,_x000D_
verticallyScrollable: y1 !== y2 || y2 !== y3_x000D_
}_x000D_
}_x000D_
function check( id ){_x000D_
alert( JSON.stringify( isScrollable( document.getElementById( id ))));_x000D_
}
_x000D_
#outer1, #outer2, #outer3 {_x000D_
background-color: pink;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
}_x000D_
#inner {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
}_x000D_
button { margin: 2em 0 0 1em; }
_x000D_
<div id="outer1" style="width: 100px; height: 100px;">_x000D_
<div id="inner">_x000D_
<button onclick="check('outer1')">check if<br>scrollable</button>_x000D_
</div>_x000D_
</div>_x000D_
<div id="outer2" style="width: 200px; height: 100px;">_x000D_
<div id="inner">_x000D_
<button onclick="check('outer2')">check if<br>scrollable</button>_x000D_
</div>_x000D_
</div>_x000D_
<div id="outer3" style="width: 100px; height: 180px;">_x000D_
<div id="inner">_x000D_
<button onclick="check('outer3')">check if<br>scrollable</button>_x000D_
</div>_x000D_
</div>
_x000D_
You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME
<script type="text/javascript">
window.alert("My name is George. Welcome!")
</script>
If you use Git and have Git Bash installed you can open a Git Bash at the directory (via Right Click in the white space in Explorer > Git Bash Here) and do:
touch .htaccess
Go to tools
>> nuget
>> console
and type:
Install-Package System.Configuration.ConfigurationManager
If you want a specific version:
Install-Package System.Configuration.ConfigurationManager -Version 4.5.0
Your ConfigurationManager
dll will now be imported and the code will begin to work.
The 'file' protocol is not a network protocol. Therefore file://192.168.1.57/~User/2ndFile.html simply does not make much sense.
Question is how you load the first file. Is that really done using a web server? Does not really sound like. If it is, then why not use the same protocol, most likely http? You cannot expect to simply switch the protocol and use two different protocols the same way...
I suspect the first file is really loaded using the apache server at all, but simply by opening the file? href="2ndFile.html" simply works because it uses a "relative url". This makes the browser use the same protocol and path as where he got the first (current) file from.
One way would be to use Array reduce..
const max = data.reduce(function(prev, current) {
return (prev.y > current.y) ? prev : current
}) //returns object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce (IE9 and above)
If you don't need to support IE (only Edge), or can use a pre-compiler such as Babel you could use the more terse syntax.
const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
this is new function so you have to add other lib file after jQuery lib
<script src="http://malsup.github.com/jquery.form.js"></script>
it will work.. I have tested.. hope it will work for you..
int
s are value types; they can never be null
. Instead, if the parsing failed, parseInt
will throw a NumberFormatException
that you need to catch.
You can use the DateTime.Parse method to get a DateTime object and then check its Month property. Do something like this:
int month = DateTime.Parse("1." + monthName + " 2008").Month;
The trick is to build a valid date to create a DateTime object.
In order to download a file to Download or Music Folder In SDCard
File downlodDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);// or DIRECTORY_PICTURES
And dont forget to add these permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For Android devices, go to your project root folder and run the command:
adb reverse tcp:[your_own_server_port] tcp:[your_own_server_port]
e.g., adb reverse tcp:8088 tcp:8088
This will make your physical device(i.e. Android phone) listen to the localhost server running on your development machine (i.e. your computer) on address http://localhost:[your_own_server_port].
After that, you can directly use http:localhost:[your_port] /your_api
in your react-native fetch(
) call.
Yes, if you do a git rm <filename>
and commit & push those changes. The file will disappear from the repository for that changeset and future commits.
The file will still be available for the previous revisions.
I got same problem if i understand your question correctly, I want to know the last inserted id after every insert performance in SQLite operation. i tried the following statement:
select * from table_name order by id desc limit 1
The id is the first column and primary key of the table_name, the mentioned statement show me the record with the largest id.
But the premise is u never deleted any row so the numbers of id equal to the numbers of rows.
Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.
upstream
in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add
. Depending on what you select for this name, your git pull
usage will change. For example, if you use:
git remote add upstream git://github.com/somename/original-project.git
then you would use this to pull changes:
git pull upstream master
But, if you choose origin for the name of the remote repo, your commands would be:
To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git
And to pull: git pull origin master
$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.
$(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
<script type = "text/javascript">
//$(window).load was deprecated in 1.8, and removed in jquery 3.0
// $(window).load(function() {
// alert("$(window).load fired");
// });
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
$(window).load fired after the $(document).ready().
$(window).load was deprecated in 1.8, and removed in jquery 3.0
I know this is an old question, and most people have replied with good answers. But for reference and hopefully saving somebody else's time. Check if your function:
$(document).ready(function(){}
is being called after you have loaded the JQuery library
use :
mongoimport -d 'database_name' -c 'collection_name' --type csv --headerline --file filepath/file_name.csv
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
I recommend to use both. Rows and cols are required and useful if the client does not support CSS. But as a designer I overwrite them to get exactly the size I wish.
The recommended way to do it is via an external stylesheet e.g.
textarea {_x000D_
width: 300px;_x000D_
height: 150px;_x000D_
}
_x000D_
<textarea> </textarea>
_x000D_
No one has mentioned it, but JavaFX does not compile or run on certain architectures deemed "servers" by Oracle (e.g. Solaris), because of the missing "jfxrt.jar" support. Stick with SWT, until further notice.
(I'm not allowed to comment yet.) I would suggest the following improvements to the already great answer of James McNellis:
template <typename Enumeration>
constexpr auto as_integer(Enumeration const value)
-> typename std::underlying_type<Enumeration>::type
{
static_assert(std::is_enum<Enumeration>::value, "parameter is not of type enum or enum class");
return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}
with
constexpr
: allowing me to use an enum member value as compile-time array sizestatic_assert
+is_enum
: to 'ensure' compile-time that the function does sth. with enumerations only, as suggestedBy the way I'm asking myself: Why should I ever use enum class
when I would like to assign number values to my enum members?! Considering the conversion effort.
Perhaps I would then go back to ordinary enum
as I suggested here: How to use enums as flags in C++?
Yet another (better) flavor of it without static_assert, based on a suggestion of @TobySpeight:
template <typename Enumeration>
constexpr std::enable_if_t<std::is_enum<Enumeration>::value,
std::underlying_type_t<Enumeration>> as_number(const Enumeration value)
{
return static_cast<std::underlying_type_t<Enumeration>>(value);
}
You should use npm run-script build
or npm build <project_folder>
. More info here: https://docs.npmjs.com/cli/build.
You can't use PHP to prevent a timeout issued by nginx.
To configure nginx to allow more time see the proxy_read_timeout
directive.
For cleaning the pasted text and replacing the currently selected text with the pasted text the matter is pretty trivial:
<div id='div' contenteditable='true' onpaste='handlepaste(this, event)'>Paste</div>
JS:
function handlepaste(el, e) {
document.execCommand('insertText', false, e.clipboardData.getData('text/plain'));
e.preventDefault();
}
First store the table in a view, then select columns from that view into a new table.
// Create a table with abitrary columns for use with the example
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= 11; i++)
table.Columns.Add("col" + i.ToString());
// Load the table with contrived data
for (int i = 0; i < 100; i++)
{
System.Data.DataRow row = table.NewRow();
for (int j = 0; j < 11; j++)
row[j] = i.ToString() + ", " + j.ToString();
table.Rows.Add(row);
}
// Create the DataView of the DataTable
System.Data.DataView view = new System.Data.DataView(table);
// Create a new DataTable from the DataView with just the columns desired - and in the order desired
System.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");
Used the sample data to test this method I found: Create ADO.NET DataView showing only selected Columns
I know this is stupidly hacky,
but if you want to support under v21, here are my achievements.
rectangle_with_10dp_radius_white_bg_and_shadow.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Shadow layers -->
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_1" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_2" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_3" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_4" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_5" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_6" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_7" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_8" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_9" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_10" />
</shape>
</item>
<!-- Background layer -->
<item>
<shape>
<solid android:color="@android:color/white" />
<corners android:radius="10dp" />
</shape>
</item>
</layer-list>
rectangle_with_10dp_radius_white_bg_and_shadow.xml (v21)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/white" />
<corners android:radius="10dp" />
</shape>
view_incoming.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/rectangle_with_10dp_radius_white_bg_and_shadow"
android:elevation="7dp"
android:gravity="center"
android:minWidth="240dp"
android:minHeight="240dp"
android:orientation="horizontal"
android:padding="16dp"
tools:targetApi="lollipop">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Hello World !" />
</LinearLayout>
Here is result:
Under v21 (this is which you made with xml)
Above v21 (real elevation rendering)
Instead of finding a way to get static variables working, I prefer to simply create a getter function. Also helpful if you need arrays belonging to a specific class, and a lot simpler to implement.
class MyClass
{
public static function getTypeList()
{
return array(
"type_a"=>"Type A",
"type_b"=>"Type B",
//... etc.
);
}
}
Wherever you need the list, simply call the getter method. For example:
if (array_key_exists($type, MyClass::getTypeList()) {
// do something important...
}
You May use set
keyword for set the path
set path=%path%;c:/wamp/bin/php/php5.3.0
if all the path are set in path variables
If you want to see all path list. you can use
set %path%
you need to append your php path behind this path.
This is how you can set environment variable.
Try to use https://www.pagedjs.org/. It polyfills page counter, header-/footer-functionality for all major browsers.
@page {
@bottom-left {
content: counter(page) ' of ' counter(pages);
}
}
It's so much more comfortable compared to alternatives like PrinceXML, Antennahouse, WeasyPrince, PDFReactor, etc ...
And it is totally free! No pricing or whatever. It really saved my life!
They seem to continuously change stuff in Chrome, but here's what works right now :-)
First you must click on the red record button or you'll get nothing.
I never noticed the WS
before but it filters out the web socket
connections.
Select it and then you can see the Frames
(now called Messages
) which will show you error messages etc.
list of all globally installed third party modules, write in console:
npm -g ls
You can also customize the card theme globally with ThemeData.cardTheme
:
MaterialApp(
title: 'savvy',
theme: ThemeData(
cardTheme: CardTheme(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(
Radius.circular(8.0),
),
),
),
// ...
As explained in "Deleting your master branch" by Matthew Brett, you need to change your GitHub repo default branch.
You need to go to the GitHub page for your forked repository, and click on the “Settings” button.
Click on the "Branches" tab on the left hand side. There’s a “Default branch” dropdown list near the top of the screen.
From there, select placeholder (where placeholder is the dummy name for your new default branch).
Confirm that you want to change your default branch.
Now you can do (from the command line):
git push origin :master
Or, since 2012, you can delete that same branch directly on GitHub:
That was announced in Sept. 2013, a year after I initially wrote that answer.
For small changes like documentation fixes, typos, or if you’re just a walking software compiler, you can get a lot done in your browser without needing to clone the entire repository to your computer.
Note: for BitBucket, Tum reports in the comments:
About the same for Bitbucket
Repo -> Settings -> Repository details -> Main branch
Heap overflow should be blame (but not always) for corrupted double-linked list
, malloc(): memory corruption
, double free or corruption (!prev)
-like glibc warnings.
It should be reproduced by the following code:
#include <vector>
using std::vector;
int main(int argc, const char *argv[])
{
int *p = new int[3];
vector<int> vec;
vec.resize(100);
p[6] = 1024;
delete[] p;
return 0;
}
if compiled using g++ (4.5.4):
$ ./heapoverflow
*** glibc detected *** ./heapoverflow: double free or corruption (!prev): 0x0000000001263030 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7af26)[0x7f853f5d3f26]
./heapoverflow[0x40138e]
./heapoverflow[0x400d9c]
./heapoverflow[0x400bd9]
./heapoverflow[0x400aa6]
./heapoverflow[0x400a26]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x7f853f57b4bd]
./heapoverflow[0x4008f9]
======= Memory map: ========
00400000-00403000 r-xp 00000000 08:02 2150398851 /data1/home/mckelvin/heapoverflow
00602000-00603000 r--p 00002000 08:02 2150398851 /data1/home/mckelvin/heapoverflow
00603000-00604000 rw-p 00003000 08:02 2150398851 /data1/home/mckelvin/heapoverflow
01263000-01284000 rw-p 00000000 00:00 0 [heap]
7f853f559000-7f853f6fa000 r-xp 00000000 09:01 201329536 /lib64/libc-2.15.so
7f853f6fa000-7f853f8fa000 ---p 001a1000 09:01 201329536 /lib64/libc-2.15.so
7f853f8fa000-7f853f8fe000 r--p 001a1000 09:01 201329536 /lib64/libc-2.15.so
7f853f8fe000-7f853f900000 rw-p 001a5000 09:01 201329536 /lib64/libc-2.15.so
7f853f900000-7f853f904000 rw-p 00000000 00:00 0
7f853f904000-7f853f919000 r-xp 00000000 09:01 74726670 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853f919000-7f853fb19000 ---p 00015000 09:01 74726670 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb19000-7f853fb1a000 r--p 00015000 09:01 74726670 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb1a000-7f853fb1b000 rw-p 00016000 09:01 74726670 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb1b000-7f853fc11000 r-xp 00000000 09:01 201329538 /lib64/libm-2.15.so
7f853fc11000-7f853fe10000 ---p 000f6000 09:01 201329538 /lib64/libm-2.15.so
7f853fe10000-7f853fe11000 r--p 000f5000 09:01 201329538 /lib64/libm-2.15.so
7f853fe11000-7f853fe12000 rw-p 000f6000 09:01 201329538 /lib64/libm-2.15.so
7f853fe12000-7f853fefc000 r-xp 00000000 09:01 74726678 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f853fefc000-7f85400fb000 ---p 000ea000 09:01 74726678 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f85400fb000-7f8540103000 r--p 000e9000 09:01 74726678 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f8540103000-7f8540105000 rw-p 000f1000 09:01 74726678 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f8540105000-7f854011a000 rw-p 00000000 00:00 0
7f854011a000-7f854013c000 r-xp 00000000 09:01 201328977 /lib64/ld-2.15.so
7f854031c000-7f8540321000 rw-p 00000000 00:00 0
7f8540339000-7f854033b000 rw-p 00000000 00:00 0
7f854033b000-7f854033c000 r--p 00021000 09:01 201328977 /lib64/ld-2.15.so
7f854033c000-7f854033d000 rw-p 00022000 09:01 201328977 /lib64/ld-2.15.so
7f854033d000-7f854033e000 rw-p 00000000 00:00 0
7fff92922000-7fff92943000 rw-p 00000000 00:00 0 [stack]
7fff929ff000-7fff92a00000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
[1] 18379 abort ./heapoverflow
and if compiled using clang++(6.0 (clang-600.0.56)):
$ ./heapoverflow
[1] 96277 segmentation fault ./heapoverflow
If you thought you might have written a bug like that, here is some hints to trace it out.
First, compile the code with debug flag(-g
):
g++ -g foo.cpp
And then, run it using valgrind:
$ valgrind ./a.out
==12693== Memcheck, a memory error detector
==12693== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12693== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==12693== Command: ./a.out
==12693==
==12693== Invalid write of size 4
==12693== at 0x400A25: main (foo.cpp:11)
==12693== Address 0x5a1c058 is 12 bytes after a block of size 12 alloc'd
==12693== at 0x4C2B800: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12693== by 0x4009F6: main (foo.cpp:8)
==12693==
==12693==
==12693== HEAP SUMMARY:
==12693== in use at exit: 0 bytes in 0 blocks
==12693== total heap usage: 2 allocs, 2 frees, 412 bytes allocated
==12693==
==12693== All heap blocks were freed -- no leaks are possible
==12693==
==12693== For counts of detected and suppressed errors, rerun with: -v
==12693== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
The bug is located in ==12693== at 0x400A25: main (foo.cpp:11)
dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
// Do some computation here.
// Update UI after computation.
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI on the main thread.
});
});
I would suggest using the members of string, but with an explicit encoding:
byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");
By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes()
etc:
EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.
Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.
EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset
instead. Using Guava I'd really use:
byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);
Yes, provided you have access to the object definition and can modify it to declare the custom event
public event EventHandler<EventArgs> ModelChanged;
And normally you'd back this up with a private method used internally to invoke the event:
private void OnModelChanged(EventArgs e)
{
if (ModelChanged != null)
ModelChanged(this, e);
}
Your code simply declares a handler for the declared myMethod
event (you can also remove the constructor), which would get invoked every time the object triggers the event.
myObject.myMethod += myNameEvent;
Similarly, you can detach a handler using
myObject.myMethod -= myNameEvent;
Also, you can write your own subclass of EventArgs
to provide specific data when your event fires.
One way is to use the multiple class selector (no space as that is the descendant selector):
.reMode_hover:not(.reMode_selected):hover _x000D_
{_x000D_
background-color: #f0ac00;_x000D_
}
_x000D_
<a href="" title="Design" class="reMode_design reMode_hover">_x000D_
<span>Design</span>_x000D_
</a>_x000D_
_x000D_
<a href="" title="Design" _x000D_
class="reMode_design reMode_hover reMode_selected">_x000D_
<span>Design</span>_x000D_
</a>
_x000D_
In C programming language, \
is used to print some of the special characters which has sepcial meaning in C. Those special characters are listed below
\\ - Backslash
\' - Single Quotation Mark
\" - Double Quatation Mark
\n - New line
\r - Carriage Return
\t - Horizontal Tab
\b - Backspace
\f - Formfeed
\a - Bell(beep) sound
Subtract 2 to it recursively until you reach either -1 or 0 (only works for positive integers obviously) :)
Try the below code snippet
<!doctype html>
<html>
<head>
<title>Audio</title>
</head>
<body>
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="http://dev.interactive-creation-works.net/1/1.ogg"></audio>
</body>
</html>
Set the href
attribute as href="javascript:;"
<ul class="product-info">
<li>
<a href="javascript:;">YOU CLICK THIS TO SHOW/HIDE</a>
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
Replace your for loop
by this :
errorCounter = Regex.Matches(yourstring,@"[a-zA-Z]").Count;
Remember to use Regex
class, you have to using System.Text.RegularExpressions;
in your import
Whoever came here (and the bountier) seemed to be looking for one-liners with not much setup, which other answers don't provide. So I'm putting forward base64.
Now, keep in mind that this is basic obfuscation only, and is in **NO WAY OK FOR SECURITY**, but here are some one-liners:
from base64 import urlsafe_b64encode, urlsafe_b64decode
def encode(data, key):
return urlsafe_b64encode(bytes(key+data, 'utf-8'))
def decode(enc, key):
return urlsafe_b64decode(enc)[len(key):].decode('utf-8')
print(encode('hi', 'there')) # b'dGhlcmVoaQ=='
print(decode(encode('hi', 'there'), 'there')) # 'hi'
A few things to note:
bytes()
and bytes::decode()
=
characters. People like me absolutely go around decoding them in the javascript console when we see them on websites. It's as easy as btoa(string)
(js)Now, if what you wanted didn't even need a key of any kind, but just some obfuscation, you can yet again just use base64, without any kinds of key:
from base64 import urlsafe_b64encode, urlsafe_b64decode
def encode(data):
return urlsafe_b64encode(bytes(data, 'utf-8'))
def decode(enc):
return urlsafe_b64decode(enc).decode()
print(encode('hi')) # b'aGk='
print(decode(encode('hi'))) # 'hi'
I know this question is resolved but, for the benefit of anyone else reading it; if you have all of the types involved as strings, you could do this as a one liner:
IYourInterface o = (Activator.CreateInstance(Type.GetType("Namespace.TaskA`1[OtherNamespace.TypeParam]") as IYourInterface);
Whenever I've done this kind of thing, I've had an interface which I wanted subsequent code to utilise, so I've casted the created instance to an interface.
I wish calling SetText
were that easy but there are quite a few gotchas that you have to deal with. You have to make sure that the thread you are calling it on is running in the STA. It can sometimes fail with an access denied error then work seconds later without problem - something to do with the COM timing issues in the clipboard. And if your application is accessed over Remote Desktop access to the clipboard is sketchy. We use a centralized method to handle all theses scenarios instead of calling SetText
directly.
@Stecy: Here's our centralized code:
The StaHelper class simply executes some arbitrary code on a thread in the Single Thread Apartment (STA) - required by the clipboard.
abstract class StaHelper
{
readonly ManualResetEvent _complete = new ManualResetEvent( false );
public void Go()
{
var thread = new Thread( new ThreadStart( DoWork ) )
{
IsBackground = true,
}
thread.SetApartmentState( ApartmentState.STA );
thread.Start();
}
// Thread entry method
private void DoWork()
{
try
{
_complete.Reset();
Work();
}
catch( Exception ex )
{
if( DontRetryWorkOnFailed )
throw;
else
{
try
{
Thread.Sleep( 1000 );
Work();
}
catch
{
// ex from first exception
LogAndShowMessage( ex );
}
}
}
finally
{
_complete.Set();
}
}
public bool DontRetryWorkOnFailed{ get; set; }
// Implemented in base class to do actual work.
protected abstract void Work();
}
Then we have a specific class for setting text on the clipboard. Creating a DataObject
manually is required in some edge cases on some versions of Windows/.NET. I don't recall the exact scenarios now and it may not be required in .NET 3.5.
class SetClipboardHelper : StaHelper
{
readonly string _format;
readonly object _data;
public SetClipboardHelper( string format, object data )
{
_format = format;
_data = data;
}
protected override void Work()
{
var obj = new System.Windows.Forms.DataObject(
_format,
_data
);
Clipboard.SetDataObject( obj, true );
}
}
Usage looks like this:
new SetClipboardHelper( DataFormats.Text, "See, I'm on the clipboard" ).Go();
Easier way to check is in browser of emulator type 10.0.2.2 instead of localhost.
Hope that helps! :)
While it's true that Collections.unmodifiableList()
works, sometimes you may have a large library having methods already defined to return arrays (e.g. String[]
).
To prevent breaking them, you can actually define auxiliary arrays that will store the values:
public class Test {
private final String[] original;
private final String[] auxiliary;
/** constructor */
public Test(String[] _values) {
original = new String[_values.length];
// Pre-allocated array.
auxiliary = new String[_values.length];
System.arraycopy(_values, 0, original, 0, _values.length);
}
/** Get array values. */
public String[] getValues() {
// No need to call clone() - we pre-allocated auxiliary.
System.arraycopy(original, 0, auxiliary, 0, original.length);
return auxiliary;
}
}
To test:
Test test = new Test(new String[]{"a", "b", "C"});
System.out.println(Arrays.asList(test.getValues()));
String[] values = test.getValues();
values[0] = "foobar";
// At this point, "foobar" exist in "auxiliary" but since we are
// copying "original" to "auxiliary" for each call, the next line
// will print the original values "a", "b", "c".
System.out.println(Arrays.asList(test.getValues()));
Not perfect, but at least you have "pseudo immutable arrays" (from the class perspective) and this will not break related code.
For one random letter, you can use:
select substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ',
(abs(checksum(newid())) % 26)+1, 1)
An important difference between using newid()
versus rand()
is that if you return multiple rows, newid()
is calculated separately for each row, while rand()
is calculated once for the whole query.
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
You can require JSON files as of Node v0.5.x (referencing this answer)
config.json:
{
"username" : "root",
"password" : "foot"
}
app.js:
var config = require('./config.json');
log_in(config.username, config.password);
These lines Worked for me.
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
//My Stuff
});
The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?
If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:
public class MyClass
{
public void doSomething(int i)
{
...
}
public void doSomething(int i, String s)
{
...
}
public void doSomething(int i, String s, boolean b)
{
...
}
}
If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:
public MyClass
{
public void doSomething(int... integers)
{
for (int i : integers)
{
...
}
}
}
Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.
ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
All you have to do is to post URL encoded username and password inside query string.
/Token/userName=johndoe%40example.com&password=1234&grant_type=password
If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.
The direct link to the WPF themes project is here: WPF themes
Download the source code (currently there is no binary release) and check out the demo that comes with it to get an idea of the capabilities.
You will need to install the WPF toolkit in order to compile and use the themes.
This is an ongoing project, so I think more themes will be added in the future. It will probably ruin the the sites trying to sell themes to you, but it is great for one man shops that can't invest too much up front.
Is there a name to describe this idiom?
In UML it is called aggregation. It differs from composition in that the member object is not owned by the referring class. In C++ you can implement aggregation in two different ways, through references or pointers.
I am assuming it is to prevent the possibly large overhead of copying a big complex object?
No, that would be a really bad reason to use this. The main reason for aggregation is that the contained object is not owned by the containing object and thus their lifetimes are not bound. In particular the referenced object lifetime must outlive the referring one. It might have been created much earlier and might live beyond the end of the lifetime of the container. Besides that, the state of the referenced object is not controlled by the class, but can change externally. If the reference is not const
, then the class can change the state of an object that lives outside of it.
Is this generally good practice? Are there any pitfalls to this approach?
It is a design tool. In some cases it will be a good idea, in some it won't. The most common pitfall is that the lifetime of the object holding the reference must never exceed the lifetime of the referenced object. If the enclosing object uses the reference after the referenced object was destroyed, you will have undefined behavior. In general it is better to prefer composition to aggregation, but if you need it, it is as good a tool as any other.
You can also use the Get-Counter cmdlet (PowerShell 2.0):
Get-Counter '\Memory\Available MBytes'
Get-Counter '\Processor(_Total)\% Processor Time'
To get a list of memory counters:
Get-Counter -ListSet *memory* | Select-Object -ExpandProperty Counter
Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...
id = cursor.lastrowid
...should work too, and it's per-connection based obviously.
Note that the ansible
command doesn't collect facts, but the ansible-playbook
command does. When running ansible -m setup
, the setup module happens to run the fact collection so you get the facts, but running ansible -m command
does not. Therefore the facts aren't available. This is why the other answers include playbook YAML files and indicate the lookup works.
This is the most simple way you can do it since you can't clear $_POST data by refreshing the page but by leaving the page and coming back to it again.
This will be on the page you would want to clear $_POST
data.
<a class="btn" href="clear_reload.php"> Clear</a> // button to 'clear' data
Now create clear_reload.php
.
clear_reload.php:
<?php
header("Location: {$_SERVER['HTTP_REFERER']}");
?>
The "clear" button will direct you to this clear_reload.php
page, which will redirect you back to the same page you were at.
You can try 'input[name="pwd"]':
function checkForm(){
var form = document.forms[0];
var selectElement = form.querySelector('input[name="pwd"]');
var selectedValue = selectElement.value;
}
take a look a this http://jsfiddle.net/2ZL4G/1/
code:
function writeData() {
jQuery("#chatTickets input:radio[id^=ticketID]:first").attr('disabled', true);
return false;
}
See also: Selector/radio, Selector/attributeStartsWith, Selector/first
my local and remote machines are both OS X. I was having trouble until I checked the file structure of the git repo that xCode Server provides me. Essentially everything is chmod 777 * in that repo so to setup a separate non xCode repo on the same machine in my remote account there I did this:
REMOTE MACHINE
LOCAL MACHINE
For me, i learned getting a clean start with a git repo on a LOCAL and REMOTE requires all initial work in a shell first. Then, after the above i was able to easily setup the LOCAL and REMOTE git repos in my IDE and do all the basic git commands using the GUI of the IDE.
I had difficulty until I started at the remote first, then did the local, and until i opened up all the permissions on remote. In addition, having the exact full path in the URL to the symlink was critical to succeed.
Again, this all worked on OS X, local and remote machines.
If Licensing is an issue you could try WINDBG for memory profiling
Even as it got the most votes, one usually can't take System.Collections.Concurrent.ConcurrentBag<T>
as a thread-safe replacement for System.Collections.Generic.List<T>
as it is (Radek Stromský already pointed it out) not ordered.
But there is a class called System.Collections.Generic.SynchronizedCollection<T>
that is already since .NET 3.0 part of the framework, but it is that well hidden in a location where one does not expect it that it is little known and probably you have never ever stumbled over it (at least I never did).
SynchronizedCollection<T>
is compiled into assembly System.ServiceModel.dll (which is part of the client profile but not of the portable class library).
As others pointed out, lxml has a pretty printer built in.
Be aware though that by default it changes CDATA sections to normal text, which can have nasty results.
Here's a Python function that preserves the input file and only changes the indentation (notice the strip_cdata=False
). Furthermore it makes sure the output uses UTF-8 as encoding instead of the default ASCII (notice the encoding='utf-8'
):
from lxml import etree
def prettyPrintXml(xmlFilePathToPrettyPrint):
assert xmlFilePathToPrettyPrint is not None
parser = etree.XMLParser(resolve_entities=False, strip_cdata=False)
document = etree.parse(xmlFilePathToPrettyPrint, parser)
document.write(xmlFilePathToPrettyPrint, pretty_print=True, encoding='utf-8')
Example usage:
prettyPrintXml('some_folder/some_file.xml')
In the bash shell, surround arithmetic expressions with $(( ... ))
$ echo $(( 7 / 3 ))
2
Although I think you are limited to integers.
It seemed quite hard to find this information, but eventually, I came across this question
You have to look at the 'System' event log, and filter by the WAS source.
Here is more info about the WAS (Windows Process Activation Service)
If the number of list items is fixed you can use the adjacent selector, e.g. if you only have three <li>
elements, you can select the last <li>
with:
#nav li+li+li {
border-bottom: 1px solid #b5b5b5;
}
seems like opening a new session is the key.
see this answer.
and here is an awesome explanation about this error
extension NSError {
static func defaultError() -> NSError {
return NSError(domain: "com.app.error.domain", code: 0, userInfo: [NSLocalizedDescriptionKey: "Something went wrong."])
}
}
which I can use NSError.defaultError()
whenever I don't have valid error object.
let error = NSError.defaultError()
print(error.localizedDescription) //Something went wrong.
I tried all of the above which did not work for me. I ended up just going with PUT (inspiration found here) and just changed my server side logic to perform a delete on this url call. (django rest framework function override).
e.g.
.put(`http://127.0.0.1:8006/api/updatetoken/20`, bayst)
.then((response) => response.data)
.catch((error) => { throw error.response.data; });
The most recent "wow" trick that I learnt is a method of doing complicated search-and-replace. Quite often in the past, I've had a really complicated regexp to do substitutions on and it's not worked. There is a better way:
:set incsearch " I have this in .vimrc
/my complicated regexp " Highlighted as you enter characters
:%s//replace with this/ " You don't have to type it again
The "trick" here (for want of a better word) is the way that you can use the search to create the regexp (and 'incsearch' highlights it as you enter characters) and then use an empty pattern in the substitution: the empty pattern defaults to the last search pattern.
Example:
/blue\(\d\+\)
:%s//red\1/
Equivalent to:
:%s/blue\(\d\+\)/red\1/
See:
:help 'incsearch'
:help :substitute
I think there's no way to do that, unless you pass the value of the JavaScript var on the URL, but it's a ugly workaround.
I think the easiest way to understand what these acronyms are supposed to mean is to forget about them for a moment. Instead, think about the software they originated with, each one of them. It really boils down to just the difference between the early web and the desktop.
As they grew in complexity in the mid-2000s, the MVC software design pattern - which was first described in the 1970s - began to be applied to web applications. Think database, HTML pages, and code inbetween. Let's refine this just a little bit to arrive at MVC: For »database«, let's assume database plus interface code. For »HTML pages«, let's assume HTML templates plus template processing code. For »code inbetween«, let's assume code mapping user clicks to actions, possibly affecting the database, definitely causing another view to be displayed. That's it, at least for the purpose of this comparison.
Let's retain one feature of this web stuff, not as it is today, but as it existed ten years ago, when JavaScript was a lowly, despicable annoyance, which real programmers did well to steer clear of: The HTML page is essentially dumb and passive. The browser is a thin client, or if you will, a poor client. There is no intelligence in the browser. Full page reloads rule. The »view« is generated anew each time around.
Let's remember that this web way, despite being all the rage, was horribly backward compared to the desktop. Desktop apps are fat clients, or rich clients, if you will. (Even a program like Microsoft Word can be thought of as some kind of client, a client for documents.) They're clients full of intelligence, full of knowledge about their data. They're stateful. They cache data they're handling in memory. No such crap as a full page reload.
And this rich desktop way is probably where the second acronym originated, MVVM. Don't be fooled by the letters, by the omission of the C. Controllers are still there. They need to be. Nothing gets removed. We just add one thing: statefulness, data cached on the client (and along with it intelligence to handle that data). That data, essentially a cache on the client, now gets called »ViewModel«. It's what allows rich interactivity. And that's it.
We can see that with Flash, Silverlight, and - most importantly - JavaScript, the web has embraced MVVM. Browsers can no longer be legitimately called thin clients. Look at their programmability. Look at their memory consumption. Look at all the Javascript interactivity on modern web pages.
Personally, I find this theory and acronym business easier to understand by looking at what it's referring to in concrete reality. Abstract concepts are useful, especially when demonstrated on concrete matter, so understanding may come full circle.
Running R under Gentoo on an AMD64. I upgraded to R 2.12.0
R version 2.12.0 (2010-10-15) Copyright (C) 2010 The R Foundation for Statistical Computing ISBN 3-900051-07-0 Platform: x86_64-pc-linux-gnu (64-bit) and those pesky messages went away.
Jan Vandermeer
I agree with what Joachim Sauer said, not possible to know (the variable type! not value type!) unless your variable is a class attribute (and you would have to retrieve class fields, get the right field by name...)
Actually for me it's totally impossible that any a.xxx().yyy()
method give you the right answer since the answer would be different on the exact same object, according to the context in which you call this method...
As teehoo said, if you know at compile a defined list of types to test you can use instanceof but you will also get subclasses returning true...
One possible solution would also be to inspire yourself from the implementation of java.lang.reflect.Field
and create your own Field
class, and then declare all your local variables as this custom Field
implementation... but you'd better find another solution, i really wonder why you need the variable type, and not just the value type?
boiled this down to a one liner sets the variable "$port389Open" to True or false - its fast and easy to replicate for a list of ports
try{$socket = New-Object Net.Sockets.TcpClient($ipAddress,389);if($socket -eq $null){$Port389Open = $false}else{Port389Open = $true;$socket.close()}}catch{Port389Open = $false}
If you want ot go really crazy you can return the an entire array-
Function StdPorts($ip){
$rst = "" | select IP,Port547Open,Port135Open,Port3389Open,Port389Open,Port53Open
$rst.IP = $Ip
try{$socket = New-Object Net.Sockets.TcpClient($ip,389);if($socket -eq $null){$rst.Port389Open = $false}else{$rst.Port389Open = $true;$socket.close();$ipscore++}}catch{$rst.Port389Open = $false}
try{$socket = New-Object Net.Sockets.TcpClient($ip,53);if($socket -eq $null){$rst.Port53Open = $false}else{$rst.Port53Open = $true;$socket.close();$ipscore++}}catch{$rst.Port53Open = $false}
try{$socket = New-Object Net.Sockets.TcpClient($ip,3389);if($socket -eq $null){$rst.Port3389Open = $false}else{$rst.Port3389Open = $true;$socket.close();$ipscore++}}catch{$rst.Port3389Open = $false}
try{$socket = New-Object Net.Sockets.TcpClient($ip,547);if($socket -eq $null){$rst.Port547Open = $false}else{$rst.Port547Open = $true;$socket.close();$ipscore++}}catch{$rst.Port547Open = $false}
try{$socket = New-Object Net.Sockets.TcpClient($ip,135);if($socket -eq $null){$rst.Port135Open = $false}else{$rst.Port135Open = $true;$socket.close();$SkipWMI = $False;$ipscore++}}catch{$rst.Port135Open = $false}
Return $rst
}
C is a macro assembler! And it's the best one!
It can do nearly everything assembly can, it can be portable and in most of the rare cases where it can't do something you can still use embedded assembly code. This leaves only a small fraction of programs that you absolutely need to write in assembly and nothing but assembly.
And the higher level abstractions and the portability make it more worthwhile for most people to write system software in C. And although you might not need portability now if you invest a lot of time and money in writing some program you might not want to limit yourself in what you'll be able to use it for in the future.
this is my solution:
var matrixRegex = /(?:matrix\(|\s*,\s*)([-+]?[0-9]*\.?[0-9]+(?:[e][-+]?[0-9]+)?)/gi;
var getMatches = function(string, regex) {
regex || (regex = matrixRegex);
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[1]);
}
return matches;
};
$.cssHooks['rotation'] = {
get: function(elem) {
var $elem = $(elem);
var matrix = getMatches($elem.css('transform'));
if (matrix.length != 6) {
return 0;
}
return Math.atan2(parseFloat(matrix[1]), parseFloat(matrix[0])) * (180/Math.PI);
},
set: function(elem, val){
var $elem = $(elem);
var deg = parseFloat(val);
if (!isNaN(deg)) {
$elem.css({ transform: 'rotate(' + deg + 'deg)' });
}
}
};
$.cssNumber.rotation = true;
$.fx.step.rotation = function(fx) {
$.cssHooks.rotation.set(fx.elem, fx.now + fx.unit);
};
then you can use it in the default animate fkt:
//rotate to 90 deg cw
$('selector').animate({ rotation: 90 });
//rotate to -90 deg ccw
$('selector').animate({ rotation: -90 });
//rotate 90 deg cw from current rotation
$('selector').animate({ rotation: '+=90' });
//rotate 90 deg ccw from current rotation
$('selector').animate({ rotation: '-=90' });
You can implement non-blocking locks using compareAndSwap (CAS) on atomic integers or longs. The "Tl2" Software Transactional Memory paper describes this:
We associate a special versioned write-lock with every transacted memory location. In its simplest form, the versioned write-lock is a single word spinlock that uses a CAS operation to acquire the lock and a store to release it. Since one only needs a single bit to indicate that the lock is taken, we use the rest of the lock word to hold a version number.
What it is describing is first read the atomic integer. Split this up into an ignored lock-bit and the version number. Attempt to CAS write it as the lock-bit cleared with the current version number to the lock-bit set and the next version number. Loop until you succeed and your are the thread which owns the lock. Unlock by setting the current version number with the lock-bit cleared. The paper describes using the version numbers in the locks to coordinate that threads have a consistent set of reads when they write.
This article describes that processors have hardware support for compare and swap operations making the very efficient. It also claims:
non-blocking CAS-based counters using atomic variables have better performance than lock-based counters in low to moderate contention
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
open cmd
type in netstat -a -n -o
find TCP [the IP address]:[port number] .... #[target_PID]#
(ditto for UDP)
(Btw, kill [target_PID]
didn't work for me)
CTRL+ALT+DELETE and choose "start task manager"
Click on "Processes" tab
Enable "PID" column by going to: View > Select Columns > Check the box for PID
Find the PID of interest and "END PROCESS"
Now you can rerun the server on [the IP address]:[port number] without a problem