string uriPath =
"file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
string localPath = new Uri(uriPath).LocalPath;
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
It can be improved like so:
if(Directory.EnumerateFileSystemEntries(ProcessingDirectory, "*.xml").ToList<string>().Count == 0)
log.Info("no files present")
Alternatively:
log.Info(Directory.EnumerateFileSystemEntries(ProcessingDirectory, "*.xml").ToList<string>().Count + " file(s) present");
Maybe it will be helpfull for you. You could use "DirectoryInfo.EnumerateFiles" method and handle UnauthorizedAccessException as you need.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
DirectoryInfo diTop = new DirectoryInfo(@"d:\");
try
{
foreach (var fi in diTop.EnumerateFiles())
{
try
{
// Display each file over 10 MB;
if (fi.Length > 10000000)
{
Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
}
}
catch (UnauthorizedAccessException UnAuthTop)
{
Console.WriteLine("{0}", UnAuthTop.Message);
}
}
foreach (var di in diTop.EnumerateDirectories("*"))
{
try
{
foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
{
try
{
// Display each file over 10 MB;
if (fi.Length > 10000000)
{
Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
}
}
catch (UnauthorizedAccessException UnAuthFile)
{
Console.WriteLine("UnAuthFile: {0}", UnAuthFile.Message);
}
}
}
catch (UnauthorizedAccessException UnAuthSubDir)
{
Console.WriteLine("UnAuthSubDir: {0}", UnAuthSubDir.Message);
}
}
}
catch (DirectoryNotFoundException DirNotFound)
{
Console.WriteLine("{0}", DirNotFound.Message);
}
catch (UnauthorizedAccessException UnAuthDir)
{
Console.WriteLine("UnAuthDir: {0}", UnAuthDir.Message);
}
catch (PathTooLongException LongPath)
{
Console.WriteLine("{0}", LongPath.Message);
}
}
}
It also means you can use reserved words as variable names
say you want a class named class, since class is a reserved word, you can instead call your class class:
IList<Student> @class = new List<Student>();
Path.GetFileNameWithoutExtension(file);
This returns the file name only without the extension type. You can also change it so you get both name and the type of file
Path.GetFileName(FileName);
source:https://msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx
The Directory.Delete method has a recursive boolean parameter, it should do what you need
There is no difference between moving and renaming; you should simply call Directory.Move
.
In general, if you're only doing a single operation, you should use the static
methods in the File
and Directory
classes instead of creating FileInfo
and DirectoryInfo
objects.
For more advice when working with files and directories, see here.
Eazy
// Create list
var myList = new List<string>();
// Add items to the list
myList.Add("item1");
myList.Add("item2");
// Convert to array
var myArray = myList.ToArray();
Thanks, everybody, for replies. I tried to use Directory.GetFiles() and Directory.GetDirectories() methods. Good news! The performance improved ~twice! 229 calls in 221ms. But also I hope, that it is possible to avoid enumeration of all items in the folder. Agree, that still the unnecessary job is executing. Don't you think so?
After all investigations, I reached a conclusion, that under pure .NET further optimiation is impossible. I am going to play with WinAPI's FindFirstFile function. Hope it will help.
Try this.
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var json = config.Formatters.JsonFormatter;
json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
config.Formatters.Remove(config.Formatters.XmlFormatter);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }
);
}
}
Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:
Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.
Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.
If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.
Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.
Right now I'm using:
TO_IGNORE=(
E201 # Whitespace after '('
E301 # Expected N blank lines, found M
E303 # Too many blank lines (pep8 gets confused by comments)
)
ARGS="--ignore `echo ${TO_IGNORE[@]} | tr ' ' ','`"
Which works, but (in the general case) will break horribly if array elements have a space in them.
(For those interested, this is a wrapper script around pep8.py)
Check this one. It will work.
function fetch($i1,$i2,$i3,$i4)
{
$input_data = '<I>
<i1>'.$i1.'</i1>
<i2>'.$i2.'</i2>
<i3>'.$i2.'</i3>
<i4>'.$i3.'</i4>
</I>';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "8080",
CURLOPT_URL => "http://192.168.1.100:8080/avaliablity",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $input_data,
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/xml"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
fetch('i1','i2','i3','i4');
It depends on the size of the file! The solutions above tend to use convenient shorthands to copy the entire file into memory, which will work in many cases.
For very large files you may need to use a streaming design where read the file by line or in chucks, process the chunks, then discard them from memory.
See the answer on reading line by line with perl if that's what you need.
Efficient way (with any number of records):
SELECT id, name, MIN(price) FROM (select * from table order by price) as t group by id
I would (and have) used IDA Pro to decompile executables. It creates semi-complete code, you can decompile to assembly or C.
If you have a copy of the debug symbols around, load those into IDA before decompiling and it will be able to name many of the functions, parameters, etc.
It also happens when you have not give enough permissions(read and write) to your sock file!
Just add expected permission to your sock contained folder and your sock file:
chmod ug+rw /path/to/your/
chmod ug+rw /path/to/your/file.sock
Then have fun!
Assuming you have a test.json
file with the following content:
{"67790": {"1": {"kwh": 319.4}}}
Then, the code below will load
the json file, update the data inside using dict.update()
and dump
into the test.json
file:
import json
a_dict = {'new_key': 'new_value'}
with open('test.json') as f:
data = json.load(f)
data.update(a_dict)
with open('test.json', 'w') as f:
json.dump(data, f)
Then, in test.json
, you'll have:
{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
Hope this is what you wanted.
Swift 4+
extension String {
func take(_ n: Int) -> String {
guard n >= 0 else {
fatalError("n should never negative")
}
let index = self.index(self.startIndex, offsetBy: min(n, self.count))
return String(self[..<index])
}
}
Returns a subsequence of the first n characters, or the entire string if the string is shorter. (inspired by: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/take.html)
Example:
let text = "Hello, World!"
let substring = text.take(5) //Hello
It depends on the protocol you're using. If you're using SVN + SSH, the SVN client can't save your password because it never touches it - the SSH client prompts you for it directly. In this case, you can use an SSH key and ssh-agent to avoid the constant prompts. If you're using the svnserve protocol or HTTP(S), then the SSH client is handling your password and can save it.
I'm using a parent pom for my projects and wanted to specify the versions in one place, so I used properties to specify the version:
parent pom:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
....
<properties>
<maven-compiler-plugin-version>2.3.2</maven-compiler-plugin-version>
</properties>
....
</project>
project pom:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
....
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin-version}</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
See also: https://www.allthingsdigital.nl/2011/04/10/maven-3-and-the-versions-dilemma/
200 megs... at which point your app grinds to a virtual halt, has about a gig working set memory, and the o/s starts to act like you'll need to reboot.
static void Main(string[] args)
{
string s = "hello world";
for(;;)
{
s = s + s.Substring(0, s.Length/10);
Console.WriteLine(s.Length);
}
}
12
13
14
15
16
17
18
...
158905664
174796230
192275853
211503438
FYI, I found I needed to put matplotlib.use('Agg')
first in Python import order. For what I was doing (unit testing needed to be headless) that meant putting
import matplotlib
matplotlib.use('Agg')
at the top of my master test script. I didn't have to touch any other files.
use:
/^[ A-Za-z0-9_@./#&+-]*$/
You can also use the character class \w to replace A-Za-z0-9_
Make your Project and Workspace to point to JDK7 which will resolve the issue. https://developers.google.com/eclipse/docs/jdk_compliance has given ways to modify Compliance and Facet level changes.
We can do something like this
string TransactionID = "BTRF"+DateTime.Now.Ticks.ToString().Substring(0, 10);
So, your real question is: "How can JavaScript save to a local file?"
Take a look at http://www.tiddlywiki.com/
They save their HTML page locally after you have "changed" it internally.
[ UPDATE 2016.01.31 ]
TiddlyWiki original version saved directly. It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename.
TiddlyWiki current version just downloads it as any file download. You need to do your own backup management. :(
[ END OF UPDATE
The trick is, you have to open the page as file:// not as http:// to be able to save locally.
The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial.
-Jesse
I had the same issue, and I uncomment extension=pdo_sqlite
and ran the migration
and everything worked fine.
if(c is TFrom)
{
// Do Stuff
}
or if you plan on using c
as a TForm
, use the following example:
var tForm = c as TForm;
if(tForm != null)
{
// c is of type TForm
}
The second example only needs to check to see if c
is of type TForm
once. Whereis if you check if see if c
is of type TForm
then cast it, the CLR undergoes an extra check.
Here is a reference.
Edit: Stolen from Jon Skeet
If you want to make sure c
is of TForm
and not any class inheriting from TForm
, then use
if(c.GetType() == typeof(TForm))
{
// Do stuff cause c is of type TForm and nothing else
}
If you want to separate the commands into one command per file, you can do
cmd /c start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1"
and in the other file, you can do
cmd /c start "" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow
The command cmd /c will close the command-prompt window after the exe was run.
What you are after is called partial function application.
Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.
Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:
Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.
This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?
Example:
var fr = partial(f, 1, 2, 3);
// now, when you invoke fr() it will invoke f(1,2,3)
fr();
Again, see that question for the details.
Try the notepad++ plugin JSMinNpp(Changed name to JSTool since 1.15)
When the toastr message poped up on the screen of firefox. the below tag was displayed in fire bug.
<div class="toast-message">Invalid Credentials, Please check Password</div>.
I took the screenshot at that time. And did the below changes in selenium java code.
String alertText = "";
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("toast-message")));
WebElement toast1 = driver.findElement(By.className("toast-message"));
alertText = toast1.getText();
System.out.println( alertText);
And my issue of toastr popup got resolved.
Sometimes JavaScript is not activated. Try something like:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"> <!--
function jActivator() {
document.getElementById("demo").onclick = function() {myFunction()};
document.getElementById("demo1").addEventListener("click", myFunction);
}
function myFunction( s ) {
document.getElementById("myresult").innerHTML = s;
}
// --> </script>
<noscript>JavaScript deactivated.</noscript>
<style type="text/css">
</style>
</head>
<body onload="jActivator()">
<ul>
<li id="demo">Click me -> onclick.</li>
<li id="demo1">Click me -> click event.</li>
<li onclick="myFunction('YOU CLICKED ME!')">Click me calling function.</li>
</ul>
<div id="myresult"> </div>
</body>
</html>
If you use the code inside a page, where no access to is possible, remove and tags and try to use 'onload=()' in a picture inside the image tag '
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
Here is another solution :
<a href="" ng-click="logout()">Sign out</a>
i.e. Just remove the # from the href attribute
.blink_text {_x000D_
_x000D_
animation:1s blinker linear infinite;_x000D_
-webkit-animation:1s blinker linear infinite;_x000D_
-moz-animation:1s blinker linear infinite;_x000D_
_x000D_
color: red;_x000D_
}_x000D_
_x000D_
@-moz-keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
@keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}
_x000D_
<span class="blink_text">India's Largest portal</span>
_x000D_
I liked @AshOoO's answer but like @Rajan Rawal I needed to preserve selected item state, if any. So I added my customization to his method AddFirstItem()
public static SelectList AddFirstItem(SelectList origList, SelectListItem firstItem)
{
List<SelectListItem> newList = origList.ToList();
newList.Insert(0, firstItem);
var selectedItem = newList.FirstOrDefault(item => item.Selected);
var selectedItemValue = String.Empty;
if (selectedItem != null)
{
selectedItemValue = selectedItem.Value;
}
return new SelectList(newList, "Value", "Text", selectedItemValue);
}
From the manual entry for PDOStatement::bindParam
:
[With
bindParam
] UnlikePDOStatement::bindValue()
, the variable is bound as a reference and will only be evaluated at the time thatPDOStatement::execute()
is called.
So, for example:
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindParam(':sex', $sex); // use bindParam to bind the variable
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'female'
or
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindValue(':sex', $sex); // use bindValue to bind the variable's value
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'male'
A lot depends on what kind of project it is. WTP's JSP support either expects the JSP files to be under the same folder that's the parent of the WEB-INF folder (src/web, which it will then treat as "/" to find TLDs), or to have project metadata set up to help it know where that root is (done for you in a Dynamic Web Project through Deployment Assembly). How are you referring to the TLD file, and where is the JSP file located?
And maybe I missed the original post to the Eclipse forums; the one I saw was posted a full day after this one.
CakePHP was intended to be used as Ruby on Rails framework clone, done in PHP, so any reverse-engineering of underlying database is pointless. EER diagrams should be reverse-engineered from Model layer.
Such tools do exist for Ruby Here you can see Redmine database EER diagrams reverse-engineered from Models. Not from database. http://redminecookbook.com/Redmine-erd-diagrams.html
With following tools: http://rails-erd.rubyforge.org/ http://railroady.prestonlee.com/
string1.equals(string2)
is the way.
It returns true
if string1
is equals to string2
in value. Else, it will return false
.
Assuming you also can't use s.union(t)
, which is equivalent to s | t
, you could try
>>> from itertools import chain
>>> set(chain(s,t))
set([1, 2, 3, 4, 5, 6])
Or, if you want a comprehension,
>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])
You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...
int i = 5; char a = ((char*)&i)[0]; char b = ((char*)&i)[1];
Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!
But you probably meant "i want to stringify a number", so ignore this response :-)
You can use ternary operator since version 1.1.5 and above like demonstrated in this little plunker (example in 1.1.5):
For history reasons (maybe plnkr.co get down for some reason in the future) here is the main code of my example:
{{true?true:false}}
Some above short anwsers is good, but it's not easy for understand, I suggest one more way:
function checkPalindrome(inputString) {
if(inputString.length == 1){
return true;
}else{
var i = 0;
var j = inputString.length -1;
while(i < j){
if(inputString[i] != inputString[j]){
return false;
}
i++;
j--;
}
}
return true;
}
I compare each character, i
start form left, j
start from right, until their index is not valid (i<j
).
It's also working in any languages
ALTER TABLE [dbo].[TableName]
ALTER COLUMN ColumnName VARCHAR(Max) NULL
Just got a solution to get height and width of a custom view:
@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
super.onSizeChanged(xNew, yNew, xOld, yOld);
viewWidth = xNew;
viewHeight = yNew;
}
Its working in my case.
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i <= yearEnd; i++) {
arr.push(i);
}
In IIS Manager click on your site. You need to be "in feature view" (rather than "content view")
In the IIS section of "feature view" choose the so-called feature "authentication" and doulbe click it. Here you can enable Windows Authentication. This is also possible (by i think in one of the suggestions in the thread) by a setting in the web.config ( ...)
But maybe you have a web.config you do not want to scrue too much around with. Then this thread wouldnt be too much help, which is why i added this answer.
just remove the breaks between li's in your html code... make the li's in one line only..
As others have answered, scatter()
or plot()
will generate the plot you want. I suggest two refinements to answers that are already here:
Use numpy to create the x-coordinate list and y-coordinate list. Working with large data sets is faster in numpy than using the iteration in Python suggested in other answers.
Use pyplot to apply the logarithmic scale rather than operating directly on the data, unless you actually want to have the logs.
import matplotlib.pyplot as plt
import numpy as np
data = [(2, 10), (3, 100), (4, 1000), (5, 100000)]
data_in_array = np.array(data)
'''
That looks like array([[ 2, 10],
[ 3, 100],
[ 4, 1000],
[ 5, 100000]])
'''
transposed = data_in_array.T
'''
That looks like array([[ 2, 3, 4, 5],
[ 10, 100, 1000, 100000]])
'''
x, y = transposed
# Here is the OO method
# You could also the state-based methods of pyplot
fig, ax = plt.subplots(1,1) # gets a handle for the AxesSubplot object
ax.plot(x, y, 'ro')
ax.plot(x, y, 'b-')
ax.set_yscale('log')
fig.show()
I've also used ax.set_xlim(1, 6)
and ax.set_ylim(.1, 1e6)
to make it pretty.
I've used the object-oriented interface to matplotlib. Because it offers greater flexibility and explicit clarity by using names of the objects created, the OO interface is preferred over the interactive state-based interface.
You can achieve spacing between columns using the col-xs-* classes,within in a col-xs-* div coded below. The spacing is consistent so that all of your columns line up correctly. To get even spacing and column size I would do the following:
<div class="container">
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
<div class="col-md-3 ">
<div class="col-md-12 well">
Some Second Content..
</div>
</div>
</div>
Docker Compose does not support the deploy
key. It's only respected when you use your version 3 YAML file in a Docker Stack.
This message is printed when you add the deploy
key to you docker-compose.yml
file and then run docker-compose up -d
WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use
docker stack deploy
to deploy to a swarm.
The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:
Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.
res
is an HttpResponse object which extends from OutgoingMessage. res.send
calls res.end
which is implemented by OutgoingMessage to send HTTP response and close connection. We see code here
I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo
. Here it is:
First, as suggested by Jimmy Zoto, my code in blade from
$article->poster->name
to
$article->poster['name']
Next is to add a second parameter in my belongsTo
,
from
return $this->belongsTo('App\User');
to
return $this->belongsTo('App\User', 'user_id');
in which user_id
is my foreign key in the news table.
Here is the sample program.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadFromConsole {
public static void main(String[] args) {
System.out.println("Enter here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String value = bufferRead.readLine();
System.out.println(value);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You can get it easily when you search in Internet. StackExchange recommends to do some research and put some effort before reaching it.
A picture is worth a thousand words:
==
equality chart:===
Equality chart:Source code to create these images:
https://github.com/sentientmachine/php_equality_charts
Those who wish to keep their sanity, read no further because none of this will make any sense, except to say that this is how the insanity-fractal, of PHP was designed.
NAN != NAN
but NAN == true
.
==
will convert left and right operands to numbers if left is a number. So 123 == "123foo"
, but "123" != "123foo"
A hex string in quotes is occasionally a float, and will be surprise cast to float against your will, causing a runtime error.
==
is not transitive because "0"== 0
, and 0 == ""
but "0" != ""
PHP Variables that have not been declared yet are false, even though PHP has a way to represent undefined variables, that feature is disabled with ==
.
"6" == " 6"
, "4.2" == "4.20"
, and "133" == "0133"
but 133 != 0133
. But "0x10" == "16"
and "1e3" == "1000"
exposing that surprise string conversion to octal will occur both without your instruction or consent, causing a runtime error.
False == 0
, ""
, []
and "0"
.
If you add 1 to number and they are already holding their maximum value, they do not wrap around, instead they are cast to infinity
.
A fresh class is == to 1.
False is the most dangerous value because False is == to most of the other variables, mostly defeating it's purpose.
If you are using PHP, Thou shalt not use the double equals operator because if you use triple equals, the only edge cases to worry about are NAN and numbers so close to their datatype's maximum value, that they are cast to infinity. With double equals, anything can be surprise ==
to anything or, or can be surprise casted against your will and !=
to something of which it should obviously be equal.
Anywhere you use ==
in PHP is a bad code smell because of the 85 bugs in it exposed by implicit casting rules that seem designed by millions of programmers programming by brownian motion.
2017: If someone is still interested in the question, my solution is the following:
const arrayToCount = [1, 2, 3, 5, 2, 8, 9, 2];_x000D_
const result = arrayToCount.filter(i => i === 2).length;_x000D_
console.log('number of the found elements: ' + result);
_x000D_
Stable sort will always return same solution (permutation) on same input.
For instance [2,1,2] will be sorted using stable sort as permutation [2,1,3] (first is index 2, then index 1 then index 3 in sorted output) That mean that output is always shuffled same way. Other non stable, but still correct permutation is [2,3,1].
Quick sort is not stable sort and permutation differences among same elements depends on algorithm for picking pivot. Some implementations pick up at random and that can make quick sort yielding different permutations on same input using same algorithm.
Stable sort algorithm is necessary deterministic.
You would have used inline styles at many places, which CSP(Content Security Policy) prohibits because it could be dangerous.
Just try removing those inline styles and put it inside dedicated stylesheet.
Another way to do it is to make an empty section right before the one you want the header on and put your header on that section. Because the section is empty the header will scroll immediately.
Install firebug and use console.log
instead of alert
. Then you will see the exact element your accessing.
An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.
WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.
The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.
If you want to set the column you filter on as a new index, you could also consider to use .filter
; if you want to keep it as a separate column then str.contains
is the way to go.
Let's say you have
df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})
ids vals
0 aball 1
1 bball 2
2 cnut 3
3 fball 4
4 ballxyz 5
and your plan is to filter all rows in which ids
contains ball
AND set ids
as new index, you can do
df.set_index('ids').filter(like='ball', axis=0)
which gives
vals
ids
aball 1
bball 2
fball 4
ballxyz 5
But filter
also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball
. In this case you use
df.set_index('ids').filter(regex='ball$', axis=0)
vals
ids
aball 1
bball 2
fball 4
Note that now the entry with ballxyz
is not included as it starts with ball
and does not end with it.
If you want to get all entries that start with ball
you can simple use
df.set_index('ids').filter(regex='^ball', axis=0)
yielding
vals
ids
ballxyz 5
The same works with columns; all you then need to change is the axis=0
part. If you filter based on columns, it would be axis=1
.
There's a difference between additive colors (http://en.wikipedia.org/wiki/Additive_color) and subtractive colors (http://en.wikipedia.org/wiki/Subtractive_color).
With additive colors, the more you add, the brighter the colors become. This is because they are emitting light. This is why the day light is (more or less) white, since the Sun is emitting in almost all the visible wavelength spectrum.
On the other hand, with subtractive colors the more colors you mix, the darker the resulting color. This is because they are reflecting light. This is also why the black colors get hotter quickly, because it absorbs (almost) all light energy and reflects (almost) none.
Specifically to your question, it depends what medium you are working on. Traditionally, additive colors (RGB) are used because the canon for computer graphics was the computer monitor, and since it's emitting light, it makes sense to use the same structure for the graphic card (the colors are shown without conversions). However, if you are used to graphic arts and press, subtractive color model is used (CMYK). In programs such as Photoshop, you can choose to work in CMYK space although it doesn't matter what color model you use: the primary colors of one group are the secondary colors of the second one and viceversa.
P.D.: my father worked at graphic arts, this is why i know this... :-P
Try the below one .it worked for me.
import zipfile, os
zipf = "compress.zip"
def main():
directory = r"Filepath"
toZip(directory)
def toZip(directory):
zippedHelp = zipfile.ZipFile(zipf, "w", compression=zipfile.ZIP_DEFLATED )
list = os.listdir(directory)
for file_list in list:
file_name = os.path.join(directory,file_list)
if os.path.isfile(file_name):
print file_name
zippedHelp.write(file_name)
else:
addFolderToZip(zippedHelp,file_list,directory)
print "---------------Directory Found-----------------------"
zippedHelp.close()
def addFolderToZip(zippedHelp,folder,directory):
path=os.path.join(directory,folder)
print path
file_list=os.listdir(path)
for file_name in file_list:
file_path=os.path.join(path,file_name)
if os.path.isfile(file_path):
zippedHelp.write(file_path)
elif os.path.isdir(file_name):
print "------------------sub directory found--------------------"
addFolderToZip(zippedHelp,file_name,path)
if __name__=="__main__":
main()
The long running most typical approach to this question is: Isolated Storage.
Serialize your control state to XML or some other format (especially easily if you're saving Dependency Properties with WPF), then save the file to the user's isolated storage.
If you do want to go the app setting route, I tried something similar at one point myself...though the below approach could easily be adapted to use Isolated Storage:
class SettingsManager
{
public static void LoadSettings(FrameworkElement sender, Dictionary<FrameworkElement, DependencyProperty> savedElements)
{
EnsureProperties(sender, savedElements);
foreach (FrameworkElement element in savedElements.Keys)
{
try
{
element.SetValue(savedElements[element], Properties.Settings.Default[sender.Name + "." + element.Name]);
}
catch (Exception ex) { }
}
}
public static void SaveSettings(FrameworkElement sender, Dictionary<FrameworkElement, DependencyProperty> savedElements)
{
EnsureProperties(sender, savedElements);
foreach (FrameworkElement element in savedElements.Keys)
{
Properties.Settings.Default[sender.Name + "." + element.Name] = element.GetValue(savedElements[element]);
}
Properties.Settings.Default.Save();
}
public static void EnsureProperties(FrameworkElement sender, Dictionary<FrameworkElement, DependencyProperty> savedElements)
{
foreach (FrameworkElement element in savedElements.Keys)
{
bool hasProperty =
Properties.Settings.Default.Properties[sender.Name + "." + element.Name] != null;
if (!hasProperty)
{
SettingsAttributeDictionary attributes = new SettingsAttributeDictionary();
UserScopedSettingAttribute attribute = new UserScopedSettingAttribute();
attributes.Add(attribute.GetType(), attribute);
SettingsProperty property = new SettingsProperty(sender.Name + "." + element.Name,
savedElements[element].DefaultMetadata.DefaultValue.GetType(), Properties.Settings.Default.Providers["LocalFileSettingsProvider"], false, null, SettingsSerializeAs.String, attributes, true, true);
Properties.Settings.Default.Properties.Add(property);
}
}
Properties.Settings.Default.Reload();
}
}
.....and....
Dictionary<FrameworkElement, DependencyProperty> savedElements = new Dictionary<FrameworkElement, DependencyProperty>();
public Window_Load(object sender, EventArgs e) {
savedElements.Add(firstNameText, TextBox.TextProperty);
savedElements.Add(lastNameText, TextBox.TextProperty);
SettingsManager.LoadSettings(this, savedElements);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
SettingsManager.SaveSettings(this, savedElements);
}
Perhaps this is easier to read:
a2.all? { |e| a1.include?(e) }
You can also use array intersection:
(a1 & a2).size == a1.size
Note that size
is used here just for speed, you can also do (slower):
(a1 & a2) == a1
But I guess the first is more readable. These 3 are plain ruby (not rails).
style="overflow: hidden"
and style="resize: none"
were the ones that did the trick.
if you have scenario in which you have to remove more then one values from the foreach array in this case you have to pass value by reference in for each: I try to explain this scenario:
foreach ($manSkuQty as $man_sku => &$man_qty) {
foreach ($manufacturerSkus as $key1 => $val1) {
// some processing here and unset first loops entries
// here dont include again for next iterations
if(some condition)
unset($manSkuQty[$key1]);
}
}
}
in second loop you want to unset first loops entries dont come again in the iteration for performance purpose or else then unset from memory as well because in memory they present and will come in iterations.
try
var lst= (from char c in source select c.ToString()).ToList();
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_user_connections
maximum range: 4,294,967,295 (e.g. 2**32 - 1)
You'd probably run out of memory, file handles, and network sockets, on your server long before you got anywhere close to that limit.
You can also do this, for readability's sake
boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());
if(!passwordVerified ){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}else{
addNewUser();
}
return passwordVerified;
This is (of course) totally VM-dependent.
Browsing through the source code of OpenJDK 7 and 8 java.util.ArrayList
, .Hashtable
, .AbstractCollection
, .PriorityQueue
, and .Vector
, you can see this claim being repeated:
/** * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
which is added by Martin Buchholz (Google) on 2010-05-09; reviewed by Chris Hegarty (Oracle).
So, probably we can say that the maximum "safe" number would be 2 147 483 639 (Integer.MAX_VALUE - 8
) and "attempts to allocate larger arrays may result in OutOfMemoryError".
(Yes, Buchholz's standalone claim does not include backing evidence, so this is a calculated appeal to authority. Even within OpenJDK itself, we can see code like return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
which shows that MAX_ARRAY_SIZE
does not yet have a real use.)
DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.
If DataRow.Table.Columns.Contains("column") Then
MsgBox("YAY")
End If
Import Module - You don't need additional efforts to fetch another thing from module. It has disadvantages such as redundant typing
Module Import From - Less typing &More control over which items of a module can be accessed.To use a new item from the module you have to update your import statement.
If your system has systemctl
sudo systemctl reload nginx
If your system supports service
(using debian/ubuntu) try this
sudo service nginx reload
If not (using centos/fedora/etc) you can try the init script
sudo /etc/init.d/nginx reload
break
will exit the loop completely, continue
will just skip the current iteration.
For example:
for (int i = 0; i < 10; i++) {
if (i == 0) {
break;
}
DoSomeThingWith(i);
}
The break will cause the loop to exit on the first iteration - DoSomeThingWith
will never be executed. This here:
for (int i = 0; i < 10; i++) {
if(i == 0) {
continue;
}
DoSomeThingWith(i);
}
Will not execute DoSomeThingWith
for i = 0
, but the loop will continue and DoSomeThingWith
will be executed for i = 1
to i = 9
.
There's a .val()
method:
If you've got an input with an id of txtEmail
you can use the following code to access the value of the text box:
$("#txtEmail").val()
You can also use the val(string)
method to set that value:
$("#txtEmail").val("something")
Have a look at the wikipedia entry here. They implement the String.Reverse extension method. This allows you to write code like this:
string s = "olleh";
s.Reverse();
They also use the ToCharArray/Reverse combination that other answers to this question suggest. The source code looks like this:
public static string Reverse(this string input)
{
char[] chars = input.ToCharArray();
Array.Reverse(chars);
return new String(chars);
}
You can use '?' to set custom parameters in string using PreparedStatments.
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
If you directly pass userID in query as you are doing then it may get attacked by SQL INJECTION Attack.
A potential problem with the two solutions offered is that, depending on how they are written, an update query may update zero records and an insert query may insert zero records. In these cases, the Inserted and Deleted recordsets will be empty. In many cases, if both the Inserted and Deleted recordsets are empty you might just want to exit the trigger without doing anything.
Since http proxy protocol is similar to raw http protocol, you can redirect desired traffic to your development server by telling firefox it's a proxy server.
two limitations:
A. this won't let you use https connections.
B. some frameworks (e,g: wordpress) don't like this method and redirect the request the wrong way
just copy the following code into a .pac file (enter your site domain and IP address, of course), and switch development/production just by changing proxy configuration.
function FindProxyForURL(url, host) {
var prox4site = {
"mysite.com":"PROXY 10.0.1.100:80",
"www.mysite.com":"PROXY 10.0.1.100:80"
}
return prox4site[host] || "DIRECT";
}
Kind of hacky, but the following should work :)
import os
filePath = "/foo/bar/baz.py"
serverPath = "/blah/boo/boom.py"
os.system("scp "+filePath+" [email protected]:"+serverPath)
Starting from Spring Boot version 1.2.0.RELEASE , there is a property you can add to your application.properties
to set a default date format to all of your classes spring.jackson.date-format
.
For your date format example, you would add this line to your properties file:
spring.jackson.date-format=yyyy-MM-dd
AD Powershell module should be listed under installed Features. See image:
.
A root-relative URL starts with a /
character, to look something like <a href="/directoryInRoot/fileName.html">link text</a>
.
The link you posted: <a href="fruits/index.html">Back to Fruits List</a>
is linking to an html file located in a directory named fruits
, the directory being in the same directory as the html page in which this link appears.
To make it a root-relative URL, change it to:
<a href="/fruits/index.html">Back to Fruits List</a>
Edited in response to question, in comments, from OP:
So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?
Yes, prefacing the URL, in the href
or src
attributes, with a /
will make the path relative to the root directory. For example, given the html page at www.example.com/fruits/apples.html
, the a
of href="/vegetables/carrots.html"
will link to the page www.example.com/vegetables/carrots.html
.
The base
tag element allows you to specify the base-uri for that page (though the base
tag would have to be added to every page in which it was necessary for to use a specific base, for this I'll simply cite the W3's example:
For example, given the following BASE declaration and A declaration:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>Our Products</TITLE>
<BASE href="http://www.aviary.com/products/intro.html">
</HEAD>
<BODY>
<P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
</BODY>
</HTML>
the relative URI "../cages/birds.gif" would resolve to:
http://www.aviary.com/cages/birds.gif
Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4.
Suggested reading:
FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.
main.c has a main wrapper like this:
#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
// the true main() routine.
}
spi.c, serial.c and usb.c have main wrappers for their respective test code like this:
#ifdef TEST_USB
int main(int argc, char *argv[]) {
// the main() routine for testing the usb code.
}
config.h Which is included by all the c files has an entry like this:
// Uncomment below to test the serial
//#define TEST_SERIAL
// Uncomment below to test the spi code
//#define TEST_SPI
// Uncomment below to test the usb code
#define TEST_USB
start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 2"
start "webpage name" "http://someurl.com/"
start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 3"
start "webpage name" "http://someurl.com/"
JAR files allow to package multiple files in order to use it as a library, plugin, or any kind of application. On the other hand, WAR files are used only for web applications.
JAR can be created with any desired structure. In contrast, WAR has a predefined structure with WEB-INF and META-INF directories.
A JAR file allows Java Runtime Environment (JRE) to deploy an entire application including the classes and the associated resources in a single request. On the other hand, a WAR file allows testing and deploying a web application easily.
If anyone is looking for a way to insert text at multiple indices in a string, try this out:
String.prototype.insertTextAtIndices = function(text) {
return this.replace(/./g, function(character, index) {
return text[index] ? text[index] + character : character;
});
};
For example, you can use this to insert <span>
tags at certain offsets in a string:
var text = {
6: "<span>",
11: "</span>"
};
"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"
I had the same issue with Golang (debugging with Goland) after migration. The only (ridiculous) thing that helped is renaming the following folder:
sudo mv /usr/local/include /usr/local/old_include
Apparently it is related to old files that homebrew installed and now broken.
For windows: just change file association of .js
file to node.exe
1) Take VSCode
2) Right click on the file in left pane
3) Click "Reveal in explorer" from context menu
4) Right click on the file -> Select "Open with" -> Select "Choose another program"
5) Check box "Always use this app to open .js file"
6) Click "More apps" -> "Look for another app in PC"
7) Navigate to node.js installation directory.(Default C:\Program Files\nodejs\node.exe"
8) Click "Open" and you can just see cmd flashing
9) Restart vscode and open the file -> Terminal Menu -> "Run active file".
I noticed some issues with this that might be useful for someone just starting, or a somewhat inexperienced user, to know. First...
CD /D "C:\Documents and Settings\%username%\Start Menu\Programs\"
two things one is that a /D after the CD may prove to be useful in making sure the directory is changed but it's not really necessary, second, if you are going to pass this from user to user you have to add, instead of your name, the code %username%, this makes the code usable on any computer, as long as they have your setup.exe file in the same location as you do on your computer. of course making sure of that is more difficult. also...
start \\filer\repo\lab\"software"\"myapp"\setup.exe
the start code here, can be set up like that, but the correct syntax is
start "\\filter\repo\lab\software\myapp\" setup.exe
This will run: setup.exe, located in: \filter\repo\lab...etc.\
Different way:
var isEven = function(number) {
// Your code goes here!
if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};
isEven(69)
This is an example that could work for you if what you need is not exactly the path, but a reference to the file working offline.
http://www.ab-d.fr/date/2008-07-12/
It is in french, but the code is javascript :)
This are the references the article points to: http://developer.mozilla.org/en/nsIDOMFile http://developer.mozilla.org/en/nsIDOMFileList
To set the use of scientific notation in your entire R session, you can use the scipen
option. From the documentation (?options
):
‘scipen’: integer. A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive
values bias towards fixed and negative towards scientific
notation: fixed notation will be preferred unless it is more
than ‘scipen’ digits wider.
So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999
:
options(scipen=999)
In C#, the common mutex used is the Monitor. The type is 'System.Threading.Monitor'. It may also be used implicitly via the 'lock(Object)' statement. One example of its use is when constructing a Singleton class.
private static readonly Object instanceLock = new Object();
private static MySingleton instance;
public static MySingleton Instance
{
lock(instanceLock)
{
if(instance == null)
{
instance = new MySingleton();
}
return instance;
}
}
The lock statement using the private lock object creates a critical section. Requiring each thread to wait until the previous is finished. The first thread will enter the section and initialize the instance. The second thread will wait, get into the section, and get the initialized instance.
Any sort of synchronization of a static member may use the lock statement similarly.
You'll have to loop over the set of columns and check each one. You should be able to get a list of all columns with a DESCRIBE table command.
Pseudo-code:
foreach $column ($cols) {
query("SELECT count(*) FROM table WHERE $column IS NOT NULL")
if($result is zero) {
# $column contains only null values"
push @onlyNullColumns, $column;
} else {
# $column contains non-null values
}
}
return @onlyNullColumns;
I know this seems a little counterintuitive but SQL does not provide a native method of selecting columns, only rows.
I recently worked on a project to read the RFID tags. The project used the Devices from manufacturers like Zebra (we were using RFD8500 ) & TSL.
More devices are from Motorola & other vendors as well!
We have to use the native SDK api's provided by the manufacturer, how it works is by pairing the device by the Bluetooth of the phones and so the data transfer between both devices take place! The programming is based on subscribe pattern where the scan should be read by the device trigger(hardware trigger) or soft trigger (from the application).
The Tag read gives us the tagId & the RSSI which is the distance factor from the RFID tags!
This is the sample app:
We get all the device paired to our Android/iOS phones :
Project ? Properties ? Target Runtimes ? Apache Tomcat worked for me. There is no Target Runtimes under Facets (I'm on Eclipse v4.2 (Juno)).
Try this. Just add an empty option. This will solve your problem.
<select onchange="jsFunction()">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>?
The better way of doing this without jQuery:
const images = document.getElementsByTagName('img');
for (let i = 0; i < images.length; i++) {
images[i].addEventListener('contextmenu', event => event.preventDefault());
}
From your output:
no listening sockets available, shutting down
what basically means, that any port in which one apache is going to be listening is already being used by another application.
netstat -punta | grep LISTEN
Will give you a list of all the ports being used and the information needed to recognize which process is so you can kill
stop
or do whatever you want to do with it.
After doing a nmap
of your ip I can see that
80/tcp open http
so I guess you sorted it out.
The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
By using the column that the index is applied to within your conditions, it will be included automatically. You do not have to use it, but it will speed up queries when it is used.
SELECT * FROM TABLE WHERE attribute = 'value'
Will use the appropriate index.
You can use :enabled pseudo-class, but notice IE<9
does not support it:
button:hover:enabled{
/*your styles*/
}
button:active:enabled{
/*your styles*/
}
In my opinion, this is the simplest way to join two tables with multiple fields:
from a in Table1 join b in Table2
on (a.Field1.ToString() + "&" + a.Field2.ToString())
equals (b.Field1.ToString() + "&" + b.Field2.ToString())
select a
Make sure you've set your locale settings right before running the script from the shell, e.g.
$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8
Docs: man locale
, man setlocale
.
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
try this ,hope it helps
select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
CASE
WHEN invitee_status=1 THEN "attending"
WHEN invitee_status=2 THEN "unsure"
WHEN invitee_status=3 THEN "declined"
WHEN invitee_status=0 THEN "notreviwed" END
) AS invitee_status
FROM your_tbl
Even they seem to identical(same implemented inteface List - non thread-safe),they give different results in terms of performance in add/delete and searching time and consuming memory (LinkedList consumes more).
LinkedLists can be used if you use highly insertion/deletion with performance O(1). ArrayLists can be used if you use direct access operations with performance O(1)
This code may make clear of these comments and you can try to understand performance results. (Sorry for boiler plate code)
public class Test {
private static Random rnd;
static {
rnd = new Random();
}
static List<String> testArrayList;
static List<String> testLinkedList;
public static final int COUNT_OBJ = 2000000;
public static void main(String[] args) {
testArrayList = new ArrayList<>();
testLinkedList = new LinkedList<>();
insertSomeDummyData(testLinkedList);
insertSomeDummyData(testArrayList);
checkInsertionPerformance(testLinkedList); //O(1)
checkInsertionPerformance(testArrayList); //O(1) -> O(n)
checkPerformanceForFinding(testArrayList); // O(1)
checkPerformanceForFinding(testLinkedList); // O(n)
}
public static void insertSomeDummyData(List<String> list) {
for (int i = COUNT_OBJ; i-- > 0; ) {
list.add(new String("" + i));
}
}
public static void checkInsertionPerformance(List<String> list) {
long startTime, finishedTime;
startTime = System.currentTimeMillis();
int rndIndex;
for (int i = 200; i-- > 0; ) {
rndIndex = rnd.nextInt(100000);
list.add(rndIndex, "test");
}
finishedTime = System.currentTimeMillis();
System.out.println(String.format("%s time passed at insertion:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));
}
public static void checkPerformanceForFinding(List<String> list) {
long startTime, finishedTime;
startTime = System.currentTimeMillis();
int rndIndex;
for (int i = 200; i-- > 0; ) {
rndIndex = rnd.nextInt(100000);
list.get(rndIndex);
}
finishedTime = System.currentTimeMillis();
System.out.println(String.format("%s time passed at searching:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));
}
}
You can group your specific layout under the correct folder structure as follows.
layout-land-target_version
ie
layout-land-19 // target KitKat
likewise you can create your layouts.
Hope this will help you
AND (both classes)
var list = document.getElementsByClassName("class1 class2");
var list = document.querySelectorAll(".class1.class2");
OR (at least one class)
var list = document.querySelectorAll(".class1,.class2");
XOR (one class but not the other)
var list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");
NAND (not both classes)
var list = document.querySelectorAll(":not(.class1),:not(.class2)");
NOR (not any of the two classes)
var list = document.querySelectorAll(":not(.class1):not(.class2)");
I think you are saying that a container
vs container-fluid
is the difference between responsive and non-responsive to the grid. This is not true...what is saying is that the width is not fixed...its full width!
This is hard to explain so lets look at the examples
Example one
container-fluid
:
So you see how the container takes up the whole screen...that's a container-fluid
.
Now lets look at the other just a normal container
and watch the edges of the preview
Example two
container
Now do you see the white space in the example? That's because its a fixed width container
! It might make more sense to open both examples up in two different tabs and switch back and forth.
EDIT
Better yet here is an example with both containers at once! Now you can really tell the difference!
I hope this helped clarify a little bit!
The function combn is in the standard utils package (i.e. already installed)
choose is also already available in the Special {base}
Check this out:
SELECT TABLE_SCHEMA ,
TABLE_NAME ,
COLUMN_NAME ,
ORDINAL_POSITION ,
COLUMN_DEFAULT ,
DATA_TYPE ,
CHARACTER_MAXIMUM_LENGTH ,
NUMERIC_PRECISION ,
NUMERIC_PRECISION_RADIX ,
NUMERIC_SCALE ,
DATETIME_PRECISION
FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA in ('dbo','meta')
and table_name in (select name from sys.tables)
order by TABLE_SCHEMA , TABLE_NAME ,ORDINAL_POSITION
You can template a struct as well as a class. However you can't template a typedef. So template<typename T> struct array {...};
works, but template<typename T> typedef struct {...} array;
does not. Note that there is no need for the typedef trick in C++ (you can use structs without the struct
modifier just fine in C++).
You can create a SUPERUSER
or promote USER
, so for your case
$ sudo -u postgres psql -c "ALTER USER myuser WITH SUPERUSER;"
or rollback
$ sudo -u postgres psql -c "ALTER USER myuser WITH NOSUPERUSER;"
To prevent a command from logging when you set password, insert a whitespace in front of it, but check that your system supports this option.
$ sudo -u postgres psql -c "CREATE USER my_user WITH PASSWORD 'my_pass';"
$ sudo -u postgres psql -c "CREATE USER my_user WITH SUPERUSER PASSWORD 'my_pass';"
Download the Visual C++ Redistributable 2015
Updated links to VC++ file:
Use caTools package in R sample code will be as follows:-
data
split = sample.split(data$DependentcoloumnName, SplitRatio = 0.6)
training_set = subset(data, split == TRUE)
test_set = subset(data, split == FALSE)
it does not allows compiler to automatic changing values of variables. a volatile variable is for dynamic use.
PHP, using MT:
$items_array = array("alpha", "bravo", "charlie");
$last_pos = count($items_array) - 1;
$random_pos = mt_rand(0, $last_pos);
$random_item = $items_array[$random_pos];
<?php
if(isset($_POST['btnSave'])){
$j = 0; //Variable for indexing uploaded image
$file_name_all="";
$target_path = "uploads/"; //Declaring Path for uploaded images
//loop to get individual element from the array
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$basename=basename($_FILES['file']['name'][$i]);
//echo"hi its base name".$basename;
$target_path = $target_path .$basename;//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < (1024*1024)) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
/***********************************************/
$file_name_all.=$target_path."*";
$filepath = rtrim($file_name_all, '*');
//echo"<img src=".$filepath." >";
/*************************************************/
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
$qry="INSERT INTO `eb_re_about_us`(`er_abt_us_id`, `er_cli_id`, `er_cli_abt_info`, `er_cli_abt_img`) VALUES (NULL,'$b1','$b5','$filepath')";
$res = mysql_query($qry,$conn);
if($res)
echo "<br/><br/>Client contact Person Information Details Saved successfully";
//header("location: nextaddclient.php");
//exit();
else
echo "<br/><br/>Client contact Person Information Details not saved successfully";
}
?>
Here $file_name_all And $filepath get 1 uplode file name 2 time?
Have you tried using the WebClient class?
you should be able to use
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);
Documentation at
http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx
We are using git-repo to manage our multiple GIT repositories. There is also a Jenkins Repo plugin that allows to checkout all or part of the repositories managed by git-repo to the same Jenkins job workspace.
I've seen the infamous "Blog in 15 minutes" video ages ago when Rails was probably around version 1.0 or something like that. One of the most important things about the Ruby/Rails world is that given it's great community it's changing ridiculously fast in comparison to other frameworks.
Today, Rails is significantly different that what it used to be, altho the main ideology has been kept the same. Having said that event tho in the lsat few years I've learnt a lot of things about Rails I still keep learning new things about it.
The most valuable resources to me that help me discovering and keeping up with the latest ways of doing Ruby and Rails are the following:
Rails Guides - A nice way of learning Rails itself, edited by the community, moderated by the core contributors. The site has a lot to offer on most of the important main topics around Rails that it can get you up and running very quickly. It covers bot the most recent stable and edge versions of the framework.
If you understand the main ideology of Rails than I definitely recommend checking out (and subscribing to) Ryan Bates' Railscasts. Let me just quote from the site itself, I think it's pretty self explanatory:
Every week Ryan Bates will host a new Railscasts episode featuring tips and tricks with Ruby on Rails. These screencasts are short and focus on one technique so you can quickly move on to applying it to your own project. The topics target the intermediate Rails developer, but beginners and experts will get something out of it as well.
There are also a lot of podcasts around Ruby/Rails, the two that I keep listening to are Ruby5 and the Ruby Show.
For more specific questions like API calls etc, I'd recommend APIDock's Rails and Ruby sections where you can get more information on specific methods.
If you are getting more familiar with the framework, it's worth taking a look at Rails Best Practices. There's a bunch of short articles on certain issues that most people make in the beginning of their learning curve with Rails. This site is meant to point pot these issues and help beginners finding their way towards writing better and more well thought out code. There's also a gem that you could use which scans your application and points out these issues and offers solutions/workarounds. Pretty neat!
These resources should help you in getting up and running with Rails. Good luck with your journey to the Rails world and welcome to the community.
if(!/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2}$/.test($(this).val())){
alert('Date format incorrect (DD/MM/YY)');
$(this).datepicker('setDate', "");
return false;
}
This code will validate date format DD/MM/YY
Use setState
in your view to change employed
property of state. This is example of React render engine.
someFunctionWhichChangeParamEmployed(isEmployed) {
this.setState({
employed: isEmployed
});
}
getInitialState() {
return {
employed: true
}
},
render(){
if (this.state.employed) {
return (
<div>
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<span>Diff me!</span>
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
A few things have changed since the top answers were added. They used to work out for me, but not quite anymore, so I have been hacking around for a bit and came up with the following solution for Ubuntu 16.04. For Ubuntu 14.04, see the comment at the bottom of the answer. Apologies if this doesn't work for shared hosting, but it seems like this is the goto answer for wkhtmltopdf installation instructions in general.
# Install dependencies
apt-get install libfontconfig \
zlib1g \
libfreetype6 \
libxrender1 \
libxext6 \
libx11-6
# TEMPORARY FIX! SEE: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/3001
apt-get install libssl1.0.0=1.0.2g-1ubuntu4.8
apt-get install libssl-dev=1.0.2g-1ubuntu4.8
# Download, extract and move binary in place
curl -L -o wkhtmltopdf.tar.xz https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar -xf wkhtmltopdf.tar.xz
mv wkhtmltox/bin/wkhtmltopdf /usr/local/bin/wkhtmltopdf
chmod +x /usr/local/bin/wkhtmltopdf
Test it out:
wkhtmltopdf http://www.google.com google.pdf
You should now have a file named google.pdf
in the current working directory.
This approach downloads the binary from the website, meaning that you can use the latest version instead of relying on package managers to be updated.
Note that as of today, my solution includes a temporary fix to this bug. I realize that the solution is really not great, but hopefully it can be removed soon. Be sure to check the status of the linked GitHub issue to see if the fix is still necessary when you read this answer!
For Ubuntu 14.04, you will need to downgrade to a different version of libssl. You can find the versions here. Anyways, be sure to consider the implications of downgrading libssl before doing so on any production server.
I hope this helps someone!
Parentheses ()
are being used in function definition:
function_name () { command1 ; command2 ; }
That is the reason you have to escape parentheses even in command parameters:
$ echo (
bash: syntax error near unexpected token `newline'
$ echo \(
(
$ echo () { command echo The command echo was redefined. ; }
$ echo anything
The command echo was redefined.
You can also by jquery:
$('#foo')[0].disabled = true;
Working example:
$('#foo')[0].disabled = true;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input id="foo" placeholder="placeholder" value="value" />
_x000D_
The problem with the answer with the most votes is it doesn't explain the reasoning for the solution.
For the lines Require ip 127.0.0.1
, you should instead add the ip address of the host that plans to access phpMyAdmin from a browser. For example Require ip 192.168.0.100
. The Require ip 127.0.0.1
allows localhost access to phpMyAdmin.
Restart apache (httpd) after making changes. I would suggest testing on localhost, or using command line tools like curl to very a http GET works, and there is no other configuration issue.
For Kotlin fans:
private fun Bitmap.addOverlay(@DimenRes marginTop: Int, @DimenRes marginLeft: Int, overlay: Bitmap): Bitmap? {
val bitmapWidth = this.width
val bitmapHeight = this.height
val marginLeft = shareBitmapWidth - overlay.width - resources.getDimension(marginLeft)
val finalBitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, this
.config)
val canvas = Canvas(finalBitmap)
canvas.drawBitmap(this, Matrix(), null)
canvas.drawBitmap(overlay, marginLeft, resources.getDimension(marginTop), null)
return finalBitmap
}
bitmap.addOverlay( R.dimen.top_margin, R.dimen.left_margin, overlayBitmap)
May be this can help:
Use MyTest
Go
select * from information_schema.COLUMNS where TABLE_NAME='employee'
{ where: MyTest= DatabaseName Employee= TableName } --Optional conditions
Beautiful solution by @Lukasz Wiklendt! Although in my case I needed something more generic so I modified it a bit:
template <class RAIter, class Compare>
vector<size_t> argSort(RAIter first, RAIter last, Compare comp) {
vector<size_t> idx(last-first);
iota(idx.begin(), idx.end(), 0);
auto idxComp = [&first,comp](size_t i1, size_t i2) {
return comp(first[i1], first[i2]);
};
sort(idx.begin(), idx.end(), idxComp);
return idx;
}
Example: Find indices sorting a vector of strings by length, except for the first element which is a dummy.
vector<string> test = {"dummy", "a", "abc", "ab"};
auto comp = [](const string &a, const string& b) {
return a.length() > b.length();
};
const auto& beginIt = test.begin() + 1;
vector<size_t> ind = argSort(beginIt, test.end(), comp);
for(auto i : ind)
cout << beginIt[i] << endl;
prints:
abc
ab
a
Make a temporary table (tempP) from a subquery
UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE P.persID IN (
SELECT tempP.tempId
FROM (
SELECT persID as tempId
FROM pers P
WHERE
P.chefID IS NOT NULL OR gehalt <
(SELECT (
SELECT MAX(gehalt * 1.05)
FROM pers MA
WHERE MA.chefID = MA.chefID)
AS _pers
)
) AS tempP
)
I've introduced a separate name (alias) and give a new name to 'persID' column for temporary table
Domain Driven Design is a methodology and process prescription for the development of complex systems whose focus is mapping activities, tasks, events, and data within a problem domain into the technology artifacts of a solution domain.
The emphasis of Domain Driven Design is to understand the problem domain in order to create an abstract model of the problem domain which can then be implemented in a particular set of technologies. Domain Driven Design as a methodology provides guidelines for how this model development and technology development can result in a system that meets the needs of the people using it while also being robust in the face of change in the problem domain.
The process side of Domain Driven Design involves the collaboration between domain experts, people who know the problem domain, and the design/architecture experts, people who know the solution domain. The idea is to have a shared model with shared language so that as people from these two different domains with their two different perspectives discuss the solution they are actually discussing a shared knowledge base with shared concepts.
The lack of a shared problem domain understanding between the people who need a particular system and the people who are designing and implementing the system seems to be a core impediment to successful projects. Domain Driven Design is a methodology to address this impediment.
It is more than having an object model. The focus is really about the shared communication and improving collaboration so that the actual needs within the problem domain can be discovered and an appropriate solution created to meet those needs.
Domain-Driven Design: The Good and The Challenging provides a brief overview with this comment:
DDD helps discover the top-level architecture and inform about the mechanics and dynamics of the domain that the software needs to replicate. Concretely, it means that a well done DDD analysis minimizes misunderstandings between domain experts and software architects, and it reduces the subsequent number of expensive requests for change. By splitting the domain complexity in smaller contexts, DDD avoids forcing project architects to design a bloated object model, which is where a lot of time is lost in working out implementation details — in part because the number of entities to deal with often grows beyond the size of conference-room white boards.
Also see this article Domain Driven Design for Services Architecture which provides a short example. The article provides the following thumbnail description of Domain Driven Design.
Domain Driven Design advocates modeling based on the reality of business as relevant to our use cases. As it is now getting older and hype level decreasing, many of us forget that the DDD approach really helps in understanding the problem at hand and design software towards the common understanding of the solution. When building applications, DDD talks about problems as domains and subdomains. It describes independent steps/areas of problems as bounded contexts, emphasizes a common language to talk about these problems, and adds many technical concepts, like entities, value objects and aggregate root rules to support the implementation.
Martin Fowler has written a number of articles in which Domain Driven Design as a methodology is mentioned. For instance this article, BoundedContext, provides an overview of the bounded context concept from Domain Driven Development.
In those younger days we were advised to build a unified model of the entire business, but DDD recognizes that we've learned that "total unification of the domain model for a large system will not be feasible or cost-effective" 1. So instead DDD divides up a large system into Bounded Contexts, each of which can have a unified model - essentially a way of structuring MultipleCanonicalModels.
Try this:
var res = list.ToDictionary(x => x, x => x);
The first lambda lets you pick the key, the second one picks the value.
You can play with it and make values differ from the keys, like this:
var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));
If your list contains duplicates, add Distinct()
like this:
var res = list.Distinct().ToDictionary(x => x, x => x);
EDIT To comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are always going to be the same, HashSet<String>
would provide a much better fit for your situation:
var res = new HashSet<string>(list);
if (res.Contains("string1")) ...
If you have the correct encoding in the string, you need not do more to get the bytes for another encoding.
public static void main(String[] args) throws Exception {
printBytes("â");
System.out.println(
new String(new byte[] { (byte) 0xE2 }, "ISO-8859-1"));
System.out.println(
new String(new byte[] { (byte) 0xC3, (byte) 0xA2 }, "UTF-8"));
}
private static void printBytes(String str) {
System.out.println("Bytes in " + str + " with ISO-8859-1");
for (byte b : str.getBytes(StandardCharsets.ISO_8859_1)) {
System.out.printf("%3X", b);
}
System.out.println();
System.out.println("Bytes in " + str + " with UTF-8");
for (byte b : str.getBytes(StandardCharsets.UTF_8)) {
System.out.printf("%3X", b);
}
System.out.println();
}
Output:
Bytes in â with ISO-8859-1
E2
Bytes in â with UTF-8
C3 A2
â
â
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";
I believe you need to have ADD COLUMN
and use AFTER
, not BEFORE
.
In case you want to place column at the beginning of a table, use the FIRST
statement:
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
FIRST";
53
stands for java-9, so it means that whatever class you have has been compiled with javac-9
and you try to run it with jre-8
. Either re-compile that class with javac-8
or use the jre-9
And for a spinner like iOs I use this:
html:
<div class='spinner'>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Css:
.spinner {
font-size: 30px;
position: relative;
display: inline-block;
width: 1em;
height: 1em;
}
.spinner div {
position: absolute;
left: 0.4629em;
bottom: 0;
width: 0.074em;
height: 0.2777em;
border-radius: 0.5em;
background-color: transparent;
-webkit-transform-origin: center -0.2222em;
-ms-transform-origin: center -0.2222em;
transform-origin: center -0.2222em;
-webkit-animation: spinner-fade 1s infinite linear;
animation: spinner-fade 1s infinite linear;
}
.spinner div:nth-child(1) {
-webkit-animation-delay: 0s;
animation-delay: 0s;
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
}
.spinner div:nth-child(2) {
-webkit-animation-delay: 0.083s;
animation-delay: 0.083s;
-webkit-transform: rotate(30deg);
-ms-transform: rotate(30deg);
transform: rotate(30deg);
}
.spinner div:nth-child(3) {
-webkit-animation-delay: 0.166s;
animation-delay: 0.166s;
-webkit-transform: rotate(60deg);
-ms-transform: rotate(60deg);
transform: rotate(60deg);
}
.spinner div:nth-child(4) {
-webkit-animation-delay: 0.249s;
animation-delay: 0.249s;
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.spinner div:nth-child(5) {
-webkit-animation-delay: 0.332s;
animation-delay: 0.332s;
-webkit-transform: rotate(120deg);
-ms-transform: rotate(120deg);
transform: rotate(120deg);
}
.spinner div:nth-child(6) {
-webkit-animation-delay: 0.415s;
animation-delay: 0.415s;
-webkit-transform: rotate(150deg);
-ms-transform: rotate(150deg);
transform: rotate(150deg);
}
.spinner div:nth-child(7) {
-webkit-animation-delay: 0.498s;
animation-delay: 0.498s;
-webkit-transform: rotate(180deg);
-ms-transform: rotate(180deg);
transform: rotate(180deg);
}
.spinner div:nth-child(8) {
-webkit-animation-delay: 0.581s;
animation-delay: 0.581s;
-webkit-transform: rotate(210deg);
-ms-transform: rotate(210deg);
transform: rotate(210deg);
}
.spinner div:nth-child(9) {
-webkit-animation-delay: 0.664s;
animation-delay: 0.664s;
-webkit-transform: rotate(240deg);
-ms-transform: rotate(240deg);
transform: rotate(240deg);
}
.spinner div:nth-child(10) {
-webkit-animation-delay: 0.747s;
animation-delay: 0.747s;
-webkit-transform: rotate(270deg);
-ms-transform: rotate(270deg);
transform: rotate(270deg);
}
.spinner div:nth-child(11) {
-webkit-animation-delay: 0.83s;
animation-delay: 0.83s;
-webkit-transform: rotate(300deg);
-ms-transform: rotate(300deg);
transform: rotate(300deg);
}
.spinner div:nth-child(12) {
-webkit-animation-delay: 0.913s;
animation-delay: 0.913s;
-webkit-transform: rotate(330deg);
-ms-transform: rotate(330deg);
transform: rotate(330deg);
}
@-webkit-keyframes spinner-fade {
0% {
background-color: #69717d;
}
100% {
background-color: transparent;
}
}
@keyframes spinner-fade {
0% {
background-color: #69717d;
}
100% {
background-color: transparent;
}
}
get from this website : https://365webresources.com/10-best-pure-css-loading-spinners-front-end-developers/
Here you go with:
from b in _dbContext.Burden
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }
This is a working twitter bootstrap 3.
Here is the javascript:
$('#myCarousel').carousel({
interval: 10000
})
$('.carousel .item').each(function(){
var next = $(this).next();
if (!next.length) {
next = $(this).siblings(':first');
}
next.children(':first-child').clone().appendTo($(this));
if (next.next().length>0) {
next.next().children(':first-child').clone().appendTo($(this));
}
else {
$(this).siblings(':first').children(':first-child').clone().appendTo($(this));
}
});
And the css:
.carousel-inner .active.left { left: -33%; }
.carousel-inner .active.right { left: 33%; }
.carousel-inner .next { left: 33% }
.carousel-inner .prev { left: -33% }
.carousel-control.left { background-image: none; }
.carousel-control.right { background-image: none; }
.carousel-inner .item { background: white; }
You can see it in action at this Jsfiddle
The reason i added this answer because the other ones don't work entirely. I found 2 bugs inside them, one of them was that the left arrow generated a strange effect and the other was about the text getting bold in some situations witch can be resolved by setting the background color so the bottom item wont be visible while the transition effect.
Change file type from tsx -> ts, jsx -> js
You can get this error if you are working on .tsx or .jsx file and you are just exporting styles etc and not jsx. In this case the error is solved by changing the file type to .ts or .js
Here's a script that will find all files matching a pattern you pass it, and then converting them from their current file encoding to UTF-8. If the encoding is US ASCII, then it will still show as US ASCII, since that is a subset of UTF-8.
#!/usr/bin/env bash
find . -name "${1}" |
while read line;
do
echo "***************************"
echo "Converting ${line}"
encoding=$(file -b --mime-encoding ${line})
echo "Found Encoding: ${encoding}"
iconv -f "${encoding}" -t "utf-8" ${line} -o ${line}.tmp
mv ${line}.tmp ${line}
done
You can avoid the unpleasant looking try/catch or regex by using the Scanner class:
String input = "123";
Scanner sc = new Scanner(input);
if (sc.hasNextInt())
System.out.println("an int: " + sc.nextInt());
else {
//handle the bad input
}
var now = DateTime.Now;
var first = new DateTime(now.Year, now.Month, 1);
var last = first.AddMonths(1).AddDays(-1);
You could also use DateTime.DaysInMonth
method:
var last = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));
Example of using PHP to get a value from a form:
Put this in foobar.php:
<html>
<body>
<form action="foobar_submit.php" method="post">
<input name="my_html_input_tag" value="PILLS HERE"/>
<input type="submit" name="my_form_submit_button"
value="Click here for penguins"/>
</form>
</body>
</html>
Read the above code so you understand what it is doing:
"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php
. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php
and the below code is run.
Put this code in foobar_submit.php in the same directory as foobar.php:
<?php
echo $_POST['my_html_input_tag'];
echo "<br><br>";
print_r($_POST);
?>
Read the above code so you know what its doing:
The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".
Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.
The value of the input tag with name=my_html_input_tag
was put into the $_POST and you retrieved it inside another PHP file.
Try this regex:
^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$
Explanation of the regex using Perl's YAPE is as below:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1 (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\+? '+' (optional (matching the most amount
possible))
----------------------------------------------------------------------
\d{1,4} digits (0-9) (between 1 and 4 times
(matching the most amount possible))
----------------------------------------------------------------------
[\s-] any character of: whitespace (\n, \r,
\t, \f, and " "), '-'
----------------------------------------------------------------------
)? end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
0+ '0' (1 or more times (matching the most
amount possible))
----------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1
or more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of
the string
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
\d{10} digits (0-9) (10 times)
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
Try this out:
grep -i 'killed process' /var/log/messages
git log --oneline | grep PATTERN
I had the same problem, and it came from a wrong client_id / Facebook App ID.
Did you switch your Facebook app to "public" or "online ? When you do so, Facebook creates a new app with a new App ID.
You can compare the "client_id" parameter value in the url with the one in your Facebook dashboard.
Also Make sure your app is public. Click on + Add product Now go to products => Facebook Login Now do the following:
Valid OAuth redirect URIs : example.com/
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
You are writing to your memory stream twice, also you are not disposing the stream after use. You are also asking the image decoder to apply embedded color correction.
Try this instead:
using (var ms = new MemoryStream(byteArrayIn))
{
return Image.FromStream(ms);
}
You can figure out the dimensions of the screen dynamically
Display mDisplay= activity.getWindowManager().getDefaultDisplay();
int width= mDisplay.getWidth();
int Height= mDisplay.getHeight();
The layout can be set using the width and the height obtained using this method.
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.
It is a little tricky. First you can use keytool to put the private key into PKCS12 format, which is more portable/compatible than Java's various keystore formats. Here is an example taking a private key with alias 'mykey' in a Java keystore and copying it into a PKCS12 file named myp12file.p12
.
[note that on most screens this command extends beyond the right side of the box: you need to scroll right to see it all]
keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
Enter destination keystore password:
Re-enter new password:
Enter source keystore password:
[Storing myp12file.p12]
Now the file myp12file.p12
contains the private key in PKCS12 format which may be used directly by many software packages or further processed using the openssl pkcs12
command. For example,
openssl pkcs12 -in myp12file.p12 -nocerts -nodes
Enter Import Password:
MAC verified OK
Bag Attributes
friendlyName: mykey
localKeyID: 54 69 6D 65 20 31 32 37 31 32 37 38 35 37 36 32 35 37
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIIC...
.
.
.
-----END RSA PRIVATE KEY-----
Prints out the private key unencrypted.
Note that this is a private key, and you are responsible for appreciating the security implications of removing it from your Java keystore and moving it around.
I stumbled upon this question trying to identify a clean way to join two assoc arrays.
I was trying to join two different tables that didn't have relationships to each other.
This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge()
+1 to him.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
$ResidentialData = $pdo->prepare($sql);
$ResidentialData->execute(array($lapi));
$ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
$CommercialData = $pdo->prepare($sql);
$CommercialData->execute(array($lapi));
$CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);
$Prospects = array_merge($ResidentialProspects,$CommercialProspects);
echo '<pre>';
var_dump($Prospects);
echo '</pre>';
Maybe this will help someone else out.
The ::
is called scope resolution operator.
Can be used like this:
::
identifier
class-name ::
identifier
namespace ::
identifier
You can read about it here
https://docs.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=vs-2017
I had the same issue. My problem was it was missing “-Dfile.encoding=UTF8” argument under the JAVA_OPTION in statWeblogic.cmd file in WebLogic server.
Putting data into a txt file worked for me
bash --version
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
curl --version
curl 7.29.0 (x86_64-redhat-linux-gnu)
cat curl_data.txt
{ "type":"index-pattern", "excludeExportDetails": true }
curl -X POST http://localhost:30560/api/saved_objects/_export -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d "$(cat curl_data.txt)" -o out.json
Another way with lodash 4.17.2
_.chain(params)
.keyBy('name')
.mapValues('input')
.value();
or
_.mapValues(_.keyBy(params, 'name'), 'input')
or with _.reduce
_.reduce(
params,
(acc, { name, input }) => ({ ...acc, [name]: input }),
{}
)
This is the most neat way in my opinion.
(for some reason Array.map doesn't work inside .then functions for me. But you can use a .forEach and [].concat() or something similar)
Promise.all([
fetch('/user/4'),
fetch('/user/5'),
fetch('/user/6'),
fetch('/user/7'),
fetch('/user/8')
]).then(responses => {
return responses.map(response => {response.json()})
}).then((values) => {
console.log(values);
})
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
If you want to write bytes then you should open the file in binary mode.
f = open('/tmp/output', 'wb')
Depending on your shell, you may be able to use the following syntax:
expr substr $string $position $length
So for your example:
TESTSTRINGONE="MOTEST"
echo `expr substr ${TESTSTRINGONE} 0 5`
Alternatively,
echo 'MOTEST' | cut -c1-5
or
echo 'MOTEST' | awk '{print substr($0,0,5)}'
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
VAR=$(scan)
Exactly the same way as for programs.
Just use:
$output = array_merge($array1, $array2);
That should solve it. Because you use string keys if one key occurs more than one time (like '44'
in your example) one key will overwrite proceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.
Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...
A workaround is to recreate the keys.
$output = array_combine($output, $output);
Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)
$output = $array1 + $array2;
All of this can be seen in: http://php.net/manual/en/function.array-merge.php
In my case I was trying to test installing a signed APK and the current installed version on my device was unsigned (building a debug version directly from Android studio)
I recently needed to create a date string with UTC and DST, and based on Sheldon's answer I put this together:
Date.prototype.getTimezone = function(showDST) {_x000D_
var jan = new Date(this.getFullYear(), 0, 1);_x000D_
var jul = new Date(this.getFullYear(), 6, 1);_x000D_
_x000D_
var utcOffset = new Date().getTimezoneOffset() / 60 * -1;_x000D_
var dstOffset = (jan.getTimezoneOffset() - jul.getTimezoneOffset()) / 60;_x000D_
_x000D_
var utc = "UTC" + utcOffset.getSign() + (utcOffset * 100).preFixed(1000);_x000D_
var dst = "DST" + dstOffset.getSign() + (dstOffset * 100).preFixed(1000);_x000D_
_x000D_
if (showDST) {_x000D_
return utc + " (" + dst + ")";_x000D_
}_x000D_
_x000D_
return utc;_x000D_
}_x000D_
Number.prototype.preFixed = function (preCeiling) {_x000D_
var num = parseInt(this, 10);_x000D_
if (preCeiling && num < preCeiling) {_x000D_
num = Math.abs(num);_x000D_
var numLength = num.toString().length;_x000D_
var preCeilingLength = preCeiling.toString().length;_x000D_
var preOffset = preCeilingLength - numLength;_x000D_
for (var i = 0; i < preOffset; i++) {_x000D_
num = "0" + num;_x000D_
}_x000D_
}_x000D_
return num;_x000D_
}_x000D_
Number.prototype.getSign = function () {_x000D_
var num = parseInt(this, 10);_x000D_
var sign = "+";_x000D_
if (num < 0) {_x000D_
sign = "-";_x000D_
}_x000D_
return sign;_x000D_
}_x000D_
_x000D_
document.body.innerHTML += new Date().getTimezone() + "<br>";_x000D_
document.body.innerHTML += new Date().getTimezone(true);
_x000D_
<p>Output for Turkey (UTC+0200) and currently in DST: UTC+0300 (DST+0100)</p>_x000D_
<hr>
_x000D_
Another situation when you may need this is if you have stl collection of pointers and want to change them using stl algorithm. Example of for_each in c++98.
struct Storage {
typedef std::list<Object*> ObjectList;
ObjectList objects;
void change() {
typedef void (*ChangeFunctionType)(Object*&);
std::for_each<ObjectList::iterator, ChangeFunctionType>
(objects.begin(), objects.end(), &Storage::changeObject);
}
static void changeObject(Object*& item) {
delete item;
item = 0;
if (someCondition) item = new Object();
}
};
Otherwise, if you use changeObject(Object* item) signature you have copy of pointer, not original one.
My bad, I had missed one part of the question.
Best, cleanest way is to use a UDF
.
Explanation within the code.
// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
("",3) ,("d",4)).map { x => Stuff(x._1,x._2) }).toDF
// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )
scala> r.show
+---+---+--------+
| a| b|notempty|
+---+---+--------+
| a| 1| 1111|
| b| 2| 1111|
| | 3| 0|
| d| 4| 1111|
+---+---+--------+
Try browser.execute_script
instead of selenium.GetEval
.
See this answer for example.
Just a note for people having the same problem as me. I've been using OpenCV/cv2 to export numpy arrays into Tiffs but I had problems with opening these Tiffs with PIL Open Image and had the same error as in the title. The problem turned out to be that PIL Open Image could not open Tiffs which was created by exporting numpy float64 arrays. When I changed it to float32, PIL could open the Tiff again.
In my situation, I have a "model", consist of several String parameters, with the exception of one: it is byte array byte[]
.
Some code snippet:
String response = args[0].toString();
Gson gson = new Gson();
BaseModel responseModel = gson.fromJson(response, BaseModel.class);
The last line above is when the
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column
is triggered. Searching through the SO, I realised I need to have some form of Adapter
to convert my BaseModel
to and fro a JsonObject. Having mixed of String
and byte[]
in a model does complicate thing. Apparently, Gson
don't really like the situation.
I end up making an Adapter
to ensure byte[]
is converted to Base64
format. Here is my Adapter
class:
public class ByteArrayToBase64Adapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
@Override
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return Base64.decode(json.getAsString(), Base64.NO_WRAP);
}
@Override
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(Base64.encodeToString(src, Base64.NO_WRAP));
}
}
To convert JSONObject to model, I used the following:
Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64Adapter()).create();
BaseModel responseModel = customGson.fromJson(response, BaseModel.class);
Similarly, to convert the model to JSONObject, I used the following:
Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64Adapter()).create();
String responseJSon = customGson.toJson(response);
What the code is doing is basically to push the intended class/object
(in this case, byte[]
class) through the Adapter
whenever it is encountered during the convertion to/fro JSONObject.
If Git for windows is installed, run Git Bash shell
:
bash
You can run ssh from within Bash shell (Bash is aware of the path of ssh)
To know the exact path of ssh, run "where" command in Bash shell:
$ where ssh
you get:
c:\Program Files\Git\usr\bin\ssh.exe
while IFS= read -r line; do echo ${#line}; done < abc.txt
It is POSIX, so it should work everywhere.
Edit: Added -r as suggested by William.
Edit: Beware of Unicode handling. Bash and zsh, with correctly set locale, will show number of codepoints, but dash will show bytes—so you have to check what your shell does. And then there many other possible definitions of length in Unicode anyway, so it depends on what you actually want.
Edit: Prefix with IFS=
to avoid losing leading and trailing spaces.
Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:
public delegate double MyFunction(double x);
public double Diff(double x, MyFunction f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
public double MyFunctionMethod(double x)
{
// Can add more complicated logic here
return x + 10;
}
public void Client()
{
double result = Diff(1.234, x => x * 456.1234);
double secondResult = Diff(2.345, MyFunctionMethod);
}
I used a little time to figure this out... I ran it some CastExceptions, but figured out that you can replace you LinearLayout in the layout.xml with the name of the class.
Like this:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/llMaster">
<com.ourshoppingnote.RelativeLayoutThatDetectsSoftKeyboard android:background="@drawable/metal_background"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:id="@+id/rlMaster" >
<LinearLayout android:layout_width="fill_parent"
android:layout_height="1dip" android:background="@drawable/line"></LinearLayout>
....
</com.ourshoppingnote.RelativeLayoutThatDetectsSoftKeyboard>
</LinearLayout>
That way you do not run into any cast issues.
... and if you don't want to do this on every page, I recommend that you use "MasterPage in Android". See the link here: http://jnastase.alner.net/archive/2011/01/08/ldquomaster-pagesrdquo-in-android.aspx
Goal: save a piece of one file to another file.
Solution:
Save selected text to the new file. Type :wSpace and the name of the new file. Actually you'll see
:'<,'>w new.txt
Then press Enter
You want to set the first character of the string to zero, like this:
char myString[10];
myString[0] = '\0';
(Or myString[0] = 0;
)
Or, actually, on initialisation, you can do:
char myString[10] = "";
But that's not a general way to set a string to zero length once it's been defined.
dynamic_cast should do the trick
TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);
The dynamic_cast
keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast.
If you attempt to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. If you attempt to cast to reference to a type that is not a type of actual object, the cast will throw a bad_cast
exception.
Make sure there is at least one virtual function in Base class to make dynamic_cast work.
Wikipedia topic Run-time type information
RTTI is available only for classes that are polymorphic, which means they have at least one virtual method. In practice, this is not a limitation because base classes must have a virtual destructor to allow objects of derived classes to perform proper cleanup if they are deleted from a base pointer.
If the data in your database is POSTED from HTML form TextArea controls, different browsers use different New Line characters:
Firefox separates lines with CHR(10) only
Internet Explorer separates lines with CHR(13) + CHR(10)
Apple (pre-OSX) separates lines with CHR(13) only
So you may need something like:
set col_name = replace(replace(col_name, CHR(13), ''), CHR(10), '')
The Swift 2 version:
// start detecting pan gesture
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(TTAltimeterDetailViewController.panGestureDetected(_:)))
panGestureRecognizer.minimumNumberOfTouches = 1
self.chartOverlayView.addGestureRecognizer(panGestureRecognizer)
func panGestureDetected(panGestureRecognizer: UIPanGestureRecognizer) {
print("pan gesture recognized")
}
Use .unshift()
to add to the beginning of an array.
TheArray.unshift(TheNewObject);
See MDN for doc on unshift()
and here for doc on other array methods.
FYI, just like there's .push()
and .pop()
for the end of the array, there's .shift()
and .unshift()
for the beginning of the array.
You can change it in you php-configuration on your webserver.
Search in php.ini
for
session.gc_maxlifetime()
The value is set in Seconds.
You wrote asp.net - are you looking to upload a file?
if so you can use the html
<input type="file" ...
You'll do it the same way you would apply a css selector. For instanse you can do
$("#mydiv > .myclass")
or
$("#mydiv .myclass")
The last one will match every myclass inside myDiv, including myclass inside myclass.
In my example i am adding an ImageView to a LinearLayout programatically. I have set top and bottom margins to ImagerView. Then adding the ImageView to the LinearLayout.
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(bitmap);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 20, 0, 40);
imageView.setLayoutParams(params);
linearLayout.addView(imageView);
Save the image details in your onPause()
or onStop()
and use it in the onCreate(Bundle savedInstanceState)
to restore the image.
EDIT:
More info on the actual process is detailed here http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle as it is different in Honeycomb than previous Android versions.
I think you can find it usefull
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
It shows how to define multiple datasources & assign one of them as primary.
Here is a rather full example, also contains distributes transactions - if you need it.
What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.
Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:
http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html
Hope these helps.
Because the question is not always supposed to be understood as the fastest technical way - I always suggest the most straightforward fastest way to understand/write: a list comprehension, one-liner
[i for i in list_from_which_to_search if i in list_to_search_in]
I had a list_to_search_in
with all the items, and wanted to return the indexes of the items in the list_from_which_to_search
.
This returns the indexes in a nice list.
There are other ways to check this problem - however list comprehensions are quick enough, adding to the fact of writing it quick enough, to solve a problem.
Open Terminal:
sudo gem update --system
It works!
Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.
Therefore, you can not use this variation
> sitemap: /sitemap.xml
Recommended syntax is
Sitemap: https://www.yourdomain.com/sitemap.xml
Note:
I think the best option is:
Create a model class as config schema
Register in DI: services.Configure(Configuration.GetSection("democonfig"));
Get the values as model object from DI in your controller:
private readonly your_model myConfig;
public DemoController(IOptions<your_model> configOps)
{
this.myConfig = configOps.Value;
}
This answer was made pre-JPA2 implementations, if you're using JPA2, see the ElementCollection answer above:
Lists of objects inside a model object are generally considered "OneToMany" relationships with another object. However, a String is not (by itself) an allowable client of a One-to-Many relationship, as it doesn't have an ID.
So, you should convert your list of Strings to a list of Argument-class JPA objects containing an ID and a String. You could potentially use the String as the ID, which would save a little space in your table both from removing the ID field and by consolidating rows where the Strings are equal, but you would lose the ability to order the arguments back into their original order (as you didn't store any ordering information).
Alternatively, you could convert your list to @Transient and add another field (argStorage) to your class that is either a VARCHAR() or a CLOB. You'll then need to add 3 functions: 2 of them are the same and should convert your list of Strings into a single String (in argStorage) delimited in a fashion that you can easily separate them. Annotate these two functions (that each do the same thing) with @PrePersist and @PreUpdate. Finally, add the third function that splits the argStorage into the list of Strings again and annotate it @PostLoad. This will keep your CLOB updated with the strings whenever you go to store the Command, and keep the argStorage field updated before you store it to the DB.
I still suggest doing the first case. It's good practice for real relationships later.
You can use Python as a quick way to host static content. On Windows, there are many options for running Python, I've personally used CygWin and ActivePython.
To use Python as a simple HTTP server just change your working directory to the folder with your static content and type python -m SimpleHTTPServer 8000
, everything in the directory will be available at http:/localhost:8000/
To do this with Python, 3.4.1 (and probably other versions of Python 3), use the http.server
module:
python -m http.server <PORT>
# or possibly:
python3 -m http.server <PORT>
# example:
python -m http.server 8080
On Windows:
py -m http.server <PORT>
I had the same error but in my case it was not related to nuget packages at all. My solution had project that had reference to other projects that were not a part of my solution and were not built. After building them with some other solution (or I could include them into my solution as well), AND re-opening my solution in visual studio the issue was resolved.
I use something like this:
SchemeRegistry sR = new SchemeRegistry();
sR.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
HttpParams params = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params, sR);
HttpClient httpclient = new DefaultHttpClient(mgr, params);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);