In my case I copied a ssl config from another machine and had the wrong IP in <VirtualHost wrong.ip.addr.here:443>
. Changed IP to what it should be, restarted httpd and the site loaded over SSL as expected.
this.$router.go()
does exactly this; if no arguments are specified, the router navigates to current location, refreshing the page.
note: current implementation of router and its history components don't mark the param as optional, but IMVHO it's either a bug or an omission on Evan You's part, since the spec explicitly allows it. I've filed an issue report about it. If you're really concerned with current TS annotations, just use the equivalent this.$router.go(0)
As to 'why is it so': go
internally passes its arguments to window.history.go
, so its equal to windows.history.go()
- which, in turn, reloads the page, as per MDN doc.
note: since this executes a "soft" reload on regular desktop (non-portable) Firefox, a bunch of strange quirks may appear if you use it but in fact you require a true reload; using the window.location.reload(true);
(https://developer.mozilla.org/en-US/docs/Web/API/Location/reload) mentioned by OP instead may help - it certainly did solve my problems on FF.
You can use the jQuery .trigger()
method. See http://api.jquery.com/trigger/
E.g.:
$('#foo').trigger('click');
Another option is to create a random mask if you just want to down-sample your data by a certain factor. Say I want to down-sample to 25% of my original data set, which is currently held in the array data_arr
:
# generate random boolean mask the length of data
# use p 0.75 for False and 0.25 for True
mask = numpy.random.choice([False, True], len(data_arr), p=[0.75, 0.25])
Now you can call data_arr[mask]
and return ~25% of the rows, randomly sampled.
If you are using Carbon you can do the following. You could also format this date to set an Expire
HTTP Header.
Carbon::parse('tomorrow midnight')->format(Carbon::RFC7231_FORMAT)
There is no trigger to perform code when the app is deleted from the device. Access to the keychain is dependant on the provisioning profile that is used to sign the application. Therefore no other applications would be able to access this information in the keychain.
It does not help with you aim to remove the password in the keychain when the user deletes application from the device but it should give you some comfort that the password is not accessible (only from a re-install of the original application).
If you want to count LOC you have written, you may need to exclude some files.
For a Django project, you may want to ignore the migrations
and static
folders. For a JavaScript project, you may exclude all pictures or all fonts.
find . \( -path '*/migrations' -o -path '*/.git' -o -path '*/.vscode' -o -path '*/fonts' -o -path '*.png' -o -path '*.jpg' -o -path '*/.github' -o -path '*/static' \) -prune -o -type f -exec cat {} + | wc -l
Usage here is as follows:
*/folder_name
*/.file_extension
To list the files, modify the latter part of the command:
find . \( -path '*/migrations' -o -path '*/.git' -o -path '*/.vscode' -o -path '*/fonts' -o -path '*.png' -o -path '*.jpg' -o -path '*/.github' -o -path '*/static' \) -prune -o --print
I was using /Date=20161003 in the folder path while doing an insert overwrite and it was failing. I changed it to /Dt=20161003 and it worked
I'm very surprised no one has mentioned:
C:\> timeout 5
N.B. Please note however (thanks Dan!) that timeout 5
means:
Sleep anywhere between 4 and 5 seconds
This can be verified empirically by putting the following into a batch file, running it repeatedly and calculating the time differences between the first and second echo
s:
@echo off
echo %time%
timeout 5 > NUL
echo %time%
If buttonSearch has no code, and only action is to return dialog result then:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
DialogResult = DialogResult.OK;
}
I think
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>Testing</div>
<div id="result" style="margin:1em 4em; background:rgb(200,200,255); height:500px"></div>
<div style="background:rgb(200,255,200); height:3000px; width:5000px;"></div>
<script>
(function(){
var link=$("#result");
var top = link.offset().top; // position from $(document).offset().top
var bottom = top + link.height(); // position from $(document).offset().top
var left = link.offset().left; // position from $(document).offset().left
var right = left + link.width(); // position from $(document).offset().left
var bottomFromBottom = $(document).height() - bottom;
// distance from document's bottom
var rightFromRight = $(document).width() - right;
// distance from document's right
var str="";
str+="top: "+top+"<br>";
str+="bottom: "+bottom+"<br>";
str+="left: "+left+"<br>";
str+="right: "+right+"<br>";
str+="bottomFromBottom: "+bottomFromBottom+"<br>";
str+="rightFromRight: "+rightFromRight+"<br>";
link.html(str);
})();
</script>
The result are
top: 44
bottom: 544
left: 72
right: 1277
bottomFromBottom: 3068
rightFromRight: 3731
in chrome browser of mine.
When the document is scrollable, $(window).height()
returns height of browser viewport, not the width of document of which some parts are hiden in scroll. See http://api.jquery.com/height/ .
That is because you are only checking the current checkbox.
Change it to
function checkUncheck() {
$('.pChk').click(function() {
if ( $('.pChk:checked').length > 0) {
$("#ProjectListButton").show();
} else {
$("#ProjectListButton").hide();
}
});
}
to check if any of the checkboxes is checked (lots of checks in this line..).
reference: http://api.jquery.com/checked-selector/
Important to note it's \n
(backslash) rather than /n
.
A lambda is part of a very important abstraction mechanism which deals with higher order functions. To get proper understanding of its value, please watch high quality lessons from Abelson and Sussman, and read the book SICP
These are relevant issues in modern software business, and becoming ever more popular.
You can use Java's Scanner
class to parse words of a file and process them in your application, and then use a BufferedWriter
or FileWriter
to write back to the file, applying the changes.
I think there is a more efficient way of getting the iterator's position of the scanner at some point, in order to better implement editting. But since files are either open for reading, or writing, I'm not sure regarding that.
In any case, you can use libraries already available for parsing of XML files, which have all of this implemented already and will allow you to do what you want easily.
Not automatically, no. You can create a project template as BlueWandered suggested or create a custom property sheet that you can use for your current and all future projects.
_CRT_SECURE_NO_WARNINGS
.Now any time you create a new project, add this property sheet like so...
The benefit here is that not only do you get a single place to manage common settings but anytime you change the settings they get propagated to ALL projects that use it. This is handy if you have a lot of settings like _CRT_SECURE_NO_WARNINGS
or libraries like Boost that you want to use in your projects.
if you need a performance trick use below:
$(".yourclass", this);
find() method makes a search everytime in selector.
Geckofx and Webkit.net were both promising at first, but they didn't keep up to date with Firefox and Chrome respectively while as Internet Explorer improved, so did the Webbrowser control, though it behaves like IE7 by default regardless of what IE version you have but that can be fixed by going into the registry and change it to IE9 allowing HTML5.
All input will be through a string. It's up to you to process that string after you've received it. Unless that is, you use the eval(input()) method, but that isn't recommended for most situations anyway.
input_string = raw_input("Enter 2 numbers here: ")
a, b = split_string_into_numbers(input_string)
do_stuff(a, b)
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
If you use Apache or something like LiteSpeed, which supports .htaccess files, you can do the following. If you don't already have a .htaccess file, you should create a new .htaccess file in your root directory (usually where your index.php is located). Now add these lines as the first rewrite rules in your .htaccess:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
You only need the instruction "RewriteEngine On" once in your .htaccess for all rewrite rules, so if you already have it, just copy the second and third line.
I hope this helps.
Regex to the rescue!
import re
s = re.sub('[^0-9a-zA-Z]+', '*', s)
Example:
>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'
How about
user r = {"",{}};
or
user r = {"",{'\0'}};
or
user r = {"",std::vector<unsigned char>()};
or
user r;
# given random variable X (house price) with population muy = 60, sigma = 40
import scipy as sc
import scipy.stats as sct
sc.version.full_version # 0.15.1
#a. Find P(X<50)
sct.norm.cdf(x=50,loc=60,scale=40) # 0.4012936743170763
#b. Find P(X>=50)
sct.norm.sf(x=50,loc=60,scale=40) # 0.5987063256829237
#c. Find P(60<=X<=80)
sct.norm.cdf(x=80,loc=60,scale=40) - sct.norm.cdf(x=60,loc=60,scale=40)
#d. how much top most 5% expensive house cost at least? or find x where P(X>=x) = 0.05
sct.norm.isf(q=0.05,loc=60,scale=40)
#e. how much top most 5% cheapest house cost at least? or find x where P(X<=x) = 0.05
sct.norm.ppf(q=0.05,loc=60,scale=40)
If you are using VS Code, close VS code and open again.
I tried closing Terminal and then opening new Terminal but it didn't work.
Re-Starting VS Code works!
it can be achieved 2 ways:
Mark the POJO to ignore unknown properties
@JsonIgnoreProperties(ignoreUnknown = true)
Configure ObjectMapper that serializes/De-serializes the POJO/json as below:
ObjectMapper mapper =new ObjectMapper();
// for Jackson version 1.X
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// for Jackson version 2.X
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
I recieved a similar error:
AttributeError: module 'pandas' has no attribute 'DataFrame'
The cause of my error was that I ran pip install of pandas as root, and my user did not have permission to the directory.
My fix was to run:
sudo chmod -R 755 /usr/local/lib/python3.6/site-packages
I'm using Bootstrap version 3.2.0 and it looks as though .navbar-inner doesn't exist any more.
The solutions here which suggest overriding .navbar-inner didn't work for me - the colour remained the same.
The colour only changed when I overrode .navbar as shown below:
.navbar {
background-color: #A4C8EC;
background-image: none;
}
Problem occurs when we want to import CommonJS module into ES6 module codebase.
Before these flags we had to import CommonJS modules with star (* as something
) import:
// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec
// transpiled js (simplified):
const moment = require("moment");
moment();
We can see that *
was somehow equivalent to exports
variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment
in our case) can be only a plain object, not callable (moment()
is not allowed).
With flag esModuleInterop
we can import CommonJS modules in compliance with es6
modules spec. Now our import code looks like this:
// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec
// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();
It works and it's perfectly valid with es6 modules spec, because moment
is not namespace from star import, it's default import.
But how does it work? As you can see, because we did a default import, we called the default
property on a moment
object. But we didn't declare a default
property on the exports
object in the moment library. The key is the __importDefault
function. It assigns module (exports
) to the default
property for CommonJS modules:
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default
key. This makes it possible to import defaults on CommonJS modules.
__importStar
does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default
property:
// index.ts file in our app
import * as moment from 'moment'
// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
And what about allowSyntheticDefaultImports
- what is it for? Now the docs should be clear:
Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
In moment
typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop
on. So allowSyntheticDefaultImports
will not report an error if we want to import default from a third-party module which doesn't have a default export.
You can do it by lodash _.head
so easily.
var arr = ['first', 'second', 'third', 'fourth', 'fifth'];_x000D_
console.log(_.head(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
If the width of the contents changes, you'll have to use this bit of code to update each column:
private void ResizeGridViewColumn(GridViewColumn column)
{
if (double.IsNaN(column.Width))
{
column.Width = column.ActualWidth;
}
column.Width = double.NaN;
}
You'd have to fire it each time the data for that column updates.
Steves answer is correct though outdated with fragments. Here is an example with FragmentDialog.
The class:
public class SomeDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setMessage("Sure you wanna do this!")
.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do nothing (will close dialog)
}
})
.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do something
}
})
.create();
}
}
To start dialog:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Create and show the dialog.
SomeDialog newFragment = new SomeDialog ();
newFragment.show(ft, "dialog");
You could also let the class implement onClickListener
and use that instead of embedded listeners.
do url_raw.cast_to_raw()
support in oracle 6
Dietrich's answer is probably just the thing you need for what you describe, sending bytes, but a closer analogue to the code you've provided for example would be using the bytearray
type.
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>>
Here's one way. You have to get the individual components from the date object (day, month & year) and then build and format the string however you wish.
n = new Date();_x000D_
y = n.getFullYear();_x000D_
m = n.getMonth() + 1;_x000D_
d = n.getDate();_x000D_
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
_x000D_
<p id="date"></p>
_x000D_
Done
upstream
in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add
. Depending on what you select for this name, your git pull
usage will change. For example, if you use:
git remote add upstream git://github.com/somename/original-project.git
then you would use this to pull changes:
git pull upstream master
But, if you choose origin for the name of the remote repo, your commands would be:
To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git
And to pull: git pull origin master
float
in SQL Server actually has [edit:almost] the precision of a "double" (in a C# sense).
float
is a synonym for float(53)
. 53 is the bits of the mantissa.
.NET double
uses 54 bits for the mantissa.
Take a look at Job Control on UNIX systems
If you don't have control of your shell, simply hitting ctrl + C should stop the process. If that doesn't work, you can try ctrl + Z and using the jobs
and kill -9 %<job #>
to kill it. The '-9' is a type of signal. You can man kill
to see a list of signals.
Spaces are used for separating Arguments. In your case C:\Program becomes argument. If your file path contains spaces then add Double quotation marks. Then cmd will recognize it as single argument.
If l
is your list and X
is your value:
for i in range(len(l) + 1):
print l[:i] + [X] + l[i:]
Just try beeprint
it prints something like this:
instance(Animal):
legs: 2,
name: 'Dog',
color: 'Spotted',
smell: 'Alot',
age: 10,
kids: 0,
I think is exactly what you need.
You can try using the WebDriver.Support SelectElement found in OpenQA.Selenium.Support.UI.Selected namespace to access the option list of a select list:
IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
SelectElement selectList = new SelectElement(elem);
IList<IWebElement> options = selectList.Options;
You can then access each option as an IWebElement, such as:
IWebElement firstOption = options[0];
Assert.AreEqual(firstOption.GetAttribute("value"), "-09:00");
I didn't see any solution which is following the principal of space complexity. If list of integers has large number of elements then it's big problem.
It will be really good to remove the integer from the List<Integer> and free
the space, once it's added to List<String>.
We can use iterator to achieve the same.
List<Integer> oldList = new ArrayList<>();
oldList.add(12);
oldList.add(14);
.......
.......
List<String> newList = new ArrayList<String>(oldList.size());
Iterator<Integer> itr = oldList.iterator();
while(itr.hasNext()){
newList.add(itr.next().toString());
itr.remove();
}
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');
Another quick test for a string to have something in it but space.
if [[ -n "${str// /}" ]]; then
echo "It is not empty!"
fi
"-n" means non-zero length string.
Then the first two slashes mean match all of the following, in our case space(s). Then the third slash is followed with the replacement (empty) string and closed with "}". Note the difference from the usual regular expression syntax.
You can read more about string manipulation in bash shell scripting here.
Change *.cs to .cs in the excludefileslist.txt
For me, this helped: I checked locale on my local shell in terminal
$ locale
LANG="cs_CZ.UTF-8"
LC_COLLATE="cs_CZ.UTF-8"
Then connected to any remote host I am using via ssh and edited file /etc/profile as root - at the end I added line:
export LANG=cs_CZ.UTF-8
After next connection it works fine in bash, ls and nano.
The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.
That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.
Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.
I had exactly the same error. My network is an internal one of a company. I downloaded neon-eclipse for java developpers. These steps worked for me:
1- I downloaded a VPN client on my PC to be totally blinded from the network. Shellfire I used. Use free account and connect to Shellserver.
2- Inside the windows firewall, I added incoming rule for Eclipse. Navigate to where eclipse exe is found.
3- Perform Maven Update project.
Then the project was able to fetch from the maven repository.
hope it helps.
PHP JSON
$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=$Videoid&key={YOUR-API-KEY}&part=statistics");
$json = json_decode($jsonURL);
First go through this one by uncommenting
//var_dump(json);
and get views count as:
$vcounts = $json->{'items'}[0]->{'statistics'}->{'viewCount'};
Just put the below simple code :
notification.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.sound_file);
For Default Sound:
notification.defaults |= Notification.DEFAULT_SOUND;
The -vm
option must occur after the other Eclipse-specific options (such as -product
, --launcher.*
, etc), but before the -vmargs
option, since everything after -vmargs
is passed directly to the JVM. Add the -vm
option on its own line and the path to your JDK executable on the following line; e.g.
-vm
C:\Program Files\Java\jdk1.8.0_161\bin\javaw.exe
-vm
optionbin
directory, not to javaw.exe
When you don't specify a virtual machine in your eclipse.ini
file, you may think that the JAVA_HOME
environment variable is used, but this is not the case!
From FAQ_How_do_I_run_Eclipse#Find_the_JVM
Eclipse DOES NOT consult the JAVA_HOME environment variable.
Instead the Windows search path will be scanned.
Recommendation
You may think it is a good idea to use the search path, because it is flexible.
While this is true, it also has the downside that the search path may be altered by installing or updating programs.
Thus, I recommend to use the explicit setting in the eclipse.ini
file.
The reason why you should specify the bin
directory and not the javaw.exe
(as proposed by many other answers), is that the launcher can then dynamically choose which is the best way to start the JVM. See details of the launcher process for all details:
We look in that directory for: (1) a default.ee file, (2) a java launcher or (3) the jvm shared library.
You can verify which VM is used by your running eclipse instance in the Configuration dialogue.
In eclipse Oxygen go to Help - About Eclipse - Installation Details - Configuration
You will see which VM path eclipse has chosen, e.g.:
eclipse.vm=C:\Program Files\Java\jdk1.8.0_161\bin\..\jre\bin\server\jvm.dll
You want to git rebase -i
to perform an interactive rebase.
If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2
, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.
Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f
and anybody sharing your code will have to jump through some hoops to pull your changes.
Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.
Use ClassLoader#getResource()
instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream
instead of InputStream
. If you can, just fix the API to ask for an InputStream
instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.
To add to @migontech's answer and also his address his comment that you could "probably make it more generic", here's a way to do it. The below will allow you to search by any property:
.filter('getByProperty', function() {
return function(propertyName, propertyValue, collection) {
var i=0, len=collection.length;
for (; i<len; i++) {
if (collection[i][propertyName] == +propertyValue) {
return collection[i];
}
}
return null;
}
});
The call to filter would then become:
var found = $filter('getByProperty')('id', fish_id, $scope.fish);
Note, I removed the unary(+) operator to allow for string-based matches...
Factor your loop logic into an iterator that yields the loop variables and returns when done -- here is a simple one that lays out images in rows/columns until we're out of images or out of places to put them:
def it(rows, cols, images):
i = 0
for r in xrange(rows):
for c in xrange(cols):
if i >= len(images):
return
yield r, c, images[i]
i += 1
for r, c, image in it(rows=4, cols=4, images=['a.jpg', 'b.jpg', 'c.jpg']):
... do something with r, c, image ...
This has the advantage of splitting up the complicated loop logic and the processing...
You can use pyautogui
or pymsgbox
:
import pyautogui
pyautogui.alert("This is a message box",title="Hello World")
Using pymsgbox
is the same as using pyautogui
:
import pymsgbox
pymsgbox.alert("This is a message box",title="Hello World")
If you want to restrict your search only to files you should consider to use -type f
in your search
try to use also -iname
for case-insensitive search
Example:
find /path -iname 'yourstring*' -type f
You could also perform some operations on results without pipe sign or xargs
Example:
Search for files and show their size in MB
find /path -iname 'yourstring*' -type f -exec du -sm {} \;
Please note that I am using windows 10. some of the following may or may not applicable for other versions of windows or operating systems:
** Note 2: **
"the Graphviz bin file address on your system" can be C:\Program Files (x86)\Graphviz2.38\bin or any other path you installed Graphviz there.
We have problem not only with Graphviz but also with other external EXE files we want to use in Jupyter.
The reason is when jupyter wants to import a package it looks in working directory to find it and when it fails to find the package it returns such errors.
What we can do is tackle this is as follows:
1) check if the Graphviz is installed on your system and if not you can download and install it from:
https://graphviz.gitlab.io/_pages/Download/Download_windows.html
and then install it. When you installing Graphviz, keep in mind where (in which folder) you are installing it.
If you see the above error when you use
import graphviz
then you have several options:
2) you can call the .exe file in the ipynb via
import os
os.environ["PATH"] += os.pathsep + r'the Graphviz bin file address on your system'
It is my experience that it is only works for the same ipynb that I am working with and every time that I open the notebook I need to call this lines of code.
3) If you want the Jupyter where to find the exe file, you need to set environmenal path.
In windows 10 you can do this going to:
Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit > New
and then add the "the Graphviz bin file address on your system"
In windows 8 or lower go to :
Control Panel > System and Security > System > Advanced System Settings > Environment Variables
and then add the ;(semicolon) + "the Graphviz bin file address on your system" to the end of path string
Note: remember to restart your machine.
4) and even this does not work, define a variable going to:
Control Panel > System and Security > System > Advanced System Settings > Environment Variables and then:
Then define a variable as this:
Remember to name the variable Graphviz. At last restart your PC and hope it works.
You're looking for delete
:
delete myhash['key2']
See the Core Javascript Guide
In Rails 3 and newer:
Rails.root
which returns a Pathname
object. If you want a string you have to add .to_s
. If you want another path in your Rails app, you can use join
like this:
Rails.root.join('app', 'assets', 'images', 'logo.png')
In Rails 2 you can use the RAILS_ROOT
constant, which is a string.
Adding a service reference allows you to create a WCF client, which can be used to talk to a regular web service provided you use the appropriate binding. Adding a web reference will allow you to create only a web service (i.e., SOAP) reference.
If you are absolutely certain you are not ready for WCF (really don't know why) then you should create a regular web service reference.
According to this link: signature help
APK Signature Scheme v2 offers:
Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files. By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing.
It is recommended to use APK Signature Scheme v2 but is not mandatory.
Although we recommend applying APK Signature Scheme v2 to your app, this new scheme is not mandatory. If your app doesn't build properly when using APK Signature Scheme v2, you can disable the new scheme.
You should be using things like: KeyEvent.VK_UP instead of the actual code.
How are you wanting to refactor it? What is the goal of the refactoring?
To force git stash pop
run this command
git stash show -p | git apply && git stash drop
Swift:
self.navigationController?.navigationBar.barTintColor = UIColor.red
self.navigationController?.navigationBar.isTranslucent = false
SELECT id FROM tbl GROUP BY cat HAVING MAX(date)
This worked for me :
npm install -g local-cors-proxy
API endpoint that we want to request that has CORS issues:
https://www.yourdomain.com/test/list
Start Proxy:
lcp --proxyUrl https://www.yourdomain.com
Proxy Active
Proxy Url: http://www.yourdomain.com:28080
Proxy Partial: proxy
PORT: 8010
Then in your client code, new API endpoint:
http://localhost:8010/proxy/test/list
End result will be a request to https://www.yourdomain.ie/test/list without the CORS issues!
Below is some simple code to execute this:
sLocation = "D:\Excel-Fso.xls"
sTxtLocation = "D:\Excel-Fso.txt"
Set ObjExl = CreateObject("Excel.Application")
Set ObjWrkBk = ObjExl.Workbooks.Open(sLocation)
Set ObjWrkSht = ObjWrkBk.workSheets("Sheet1")
ObjExl.Visible = True
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSOFile = FSO.CreateTextFile (sTxtLocation)
sRowCnt = ObjWrkSht.usedRange.Rows.Count
sColCnt = ObjWrkSht.usedRange.Columns.Count
For iLoop = 1 to sRowCnt
For jLoop = 1 to sColCnt
FSOFile.Write(ObjExl.Cells(iLoop,jLoop).value) & vbtab
Next
Next
Set ObjWrkBk = Nothing
Set ObjWrkSht = Nothing
Set ObjExl = Nothing
Set FSO = Nothing
Set FSOFile = Nothing
I think it is best way for you.
You should add this: this.onTodoChange = this.onTodoChange.bind(this)
.
And your function has event param(e)
, and get value:
componentWillMount(){
this.setState({
updatable : false,
name : this.props.name,
status : this.props.status
});
this.onTodoChange = this.onTodoChange.bind(this)
}
<input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={this.onTodoChange}/>
onTodoChange(e){
const {name, value} = e.target;
this.setState({[name]: value});
}
One approach would be to just use the ModelState
:
ModelState.AddModelError("", "Error in cloud - GetPLUInfo" + ex.Message);
and then on the view do something like this:
@Html.ValidationSummary()
where you want the errors to display. If there are no errors, it won't display, but if there are you'll get a section that lists all the errors.
You can't really do this without some form of scripting to the best of my knowledge.
<form id="my_form">
<!-- Your Form -->
<a href="javascript:{}" onclick="document.getElementById('my_form').submit(); return false;">submit</a>
</form>
Example from Here.
Using the .val()
function on a multi-select list will return an array of the selected values:
var selectedValues = $('#multipleSelect').val();
and in your html:
<select id="multipleSelect" multiple="multiple">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
NW.js allows you to create desktop applications using Javascript without all the security restrictions usually placed on the browser. So you can run executables with a function, or create/edit/read/write/delete files. You can access the hardware, such as current CPU usage or total ram in use, etc.
You can create a windows, linux, or mac desktop application with it that doesn't require any installation.
Your css is fine, but I think it's not applying on divs. Just write simple class name and then try. You can check it at Jsfiddle.
.left {
float: left;
width: 125px;
text-align: right;
margin: 2px 10px;
display: inline;
}
.right {
float: left;
text-align: left;
margin: 2px 10px;
display: inline;
}
The quick and dirty way is using json_encode
and json_decode
which will turn the entire array (including sub elements) into an object.
$clasa = json_decode(json_encode($clasa)); //Turn it into an object
The same can be used to convert an object into an array. Simply add , true
to json_decode
to return an associated array:
$clasa = json_decode(json_encode($clasa), true); //Turn it into an array
An alternate way (without being dirty) is simply a recursive function:
function convertToObject($array) {
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = convertToObject($value);
}
$object->$key = $value;
}
return $object;
}
or in full code:
<?php
function convertToObject($array) {
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = convertToObject($value);
}
$object->$key = $value;
}
return $object;
}
$clasa = array(
'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);
$obj = convertToObject($clasa);
print_r($obj);
?>
which outputs (note that there's no arrays - only stdClass
's):
stdClass Object
(
[e1] => stdClass Object
(
[nume] => Nitu
[prenume] => Andrei
[sex] => m
[varsta] => 23
)
[e2] => stdClass Object
(
[nume] => Nae
[prenume] => Ionel
[sex] => m
[varsta] => 27
)
[e3] => stdClass Object
(
[nume] => Noman
[prenume] => Alice
[sex] => f
[varsta] => 22
)
[e4] => stdClass Object
(
[nume] => Geangos
[prenume] => Bogdan
[sex] => m
[varsta] => 23
)
[e5] => stdClass Object
(
[nume] => Vasile
[prenume] => Mihai
[sex] => m
[varsta] => 25
)
)
So you'd refer to it by $obj->e5->nume
.
Internet Explorer doesn't fully support Flexbox due to:
Partial support is due to large amount of bugs present (see known issues).
Screenshot and infos taken from caniuse.com
Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
property. See bug.flex
is 0 0 auto
rather than 0 1 auto
as defined in the latest spec.min-height
is used. See bug.Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.
align-items: center
overflow their containermin-height
on a flex container won't apply to its flex itemsflex
shorthand declarations with unitless flex-basis
values are ignoredflex
items don't always preserve intrinsic aspect ratiosflex-basis
doesn't account for box-sizing: border-box
flex-basis
doesn't support calc()
align-items: baseline
doesn't work with nested flex containersflex-flow: column wrap
do not contain their itemsmargin: auto
on the cross axisflex-basis
cannot be animatedmax-width
is usedUse iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
Have you tried using JavaScriptSerializer
?
There's also DataContractJsonSerializer
i use this code, which relies on the library "JQuery":
$(document).on('change', 'select', function () {
let next_select = $(this);
// console.log(next_select.toArray())
if (!next_select.parent().parent().next().find('select').length) {
next_select.parent().parent().parent().next().find('input[type="text"]').click()
console.log(next_select.parent().parent().parent().next());
} else if (next_select.parent().parent().next().find('select').prop("disabled")) {
setTimeout(function () {
next_select.parent().parent().next().find('select').select2('open')
}, 1000)
console.log('b');
} else if (next_select.parent().parent().next().find('select').length) {
next_select.parent().parent().next().find('select').select2('open')
console.log('c');
}
});
ls -lR
is to display all files, directories and sub directories of the current directory
ls -lR | more
is used to show all the files in a flow.
Your this
doesn't refer to the element in the step callback, instead you want to keep a reference to it at the beginning of your function (wrapped in $this
in my example):
$('.Count').each(function () {
var $this = $(this);
jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
duration: 1000,
easing: 'swing',
step: function () {
$this.text(Math.ceil(this.Counter));
}
});
});
Update: If you want to display decimal numbers, then instead of rounding the value with Math.ceil
you can round up to 2 decimals for instance with value.toFixed(2)
:
step: function () {
$this.text(this.Counter.toFixed(2));
}
apache commons lang has a class SystemUtils.java you can use :
SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS
I had a list of dataframes with no common id column.
I had missing data on many dfs. There were Null values.
The dataframes were produced using table function.
The Reduce, Merging, rbind, rbind.fill, and their like could not help me to my aim.
My aim was to produce an understandable merged dataframe, irrelevant of the missing data and common id column.
Therefore, I made the following function. Maybe this function can help someone.
##########################################################
#### Dependencies #####
##########################################################
# Depends on Base R only
##########################################################
#### Example DF #####
##########################################################
# Example df
ex_df <- cbind(c( seq(1, 10, 1), rep("NA", 0), seq(1,10, 1) ),
c( seq(1, 7, 1), rep("NA", 3), seq(1, 12, 1) ),
c( seq(1, 3, 1), rep("NA", 7), seq(1, 5, 1), rep("NA", 5) ))
# Making colnames and rownames
colnames(ex_df) <- 1:dim(ex_df)[2]
rownames(ex_df) <- 1:dim(ex_df)[1]
# Making an unequal list of dfs,
# without a common id column
list_of_df <- apply(ex_df=="NA", 2, ( table) )
it is following the function
##########################################################
#### The function #####
##########################################################
# The function to rbind it
rbind_null_df_lists <- function ( list_of_dfs ) {
length_df <- do.call(rbind, (lapply( list_of_dfs, function(x) length(x))))
max_no <- max(length_df[,1])
max_df <- length_df[max(length_df),]
name_df <- names(length_df[length_df== max_no,][1])
names_list <- names(list_of_dfs[ name_df][[1]])
df_dfs <- list()
for (i in 1:max_no ) {
df_dfs[[i]] <- do.call(rbind, lapply(1:length(list_of_dfs), function(x) list_of_dfs[[x]][i]))
}
df_cbind <- do.call( cbind, df_dfs )
rownames( df_cbind ) <- rownames (length_df)
colnames( df_cbind ) <- names_list
df_cbind
}
Running the example
##########################################################
#### Running the example #####
##########################################################
rbind_null_df_lists ( list_of_df )
You need to use the border property as seen here: jsFiddle
HTML:
<table width="770">
<tr>
<td class="border-left-bottom">picture (border only to the left and bottom ) </td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td class="border-left-bottom">picture (border only to the left and bottom) </td>
</tr>
</table>`
CSS:
td.border-left-bottom{
border-left: solid 1px #000;
border-bottom: solid 1px #000;
}
The maximum SqlDbType.VarChar size is 2147483647.
If you would use a generic oledb connection instead of sql, I found here there is also a LongVarChar datatype. Its max size is 2147483647.
cmd.Parameters.Add("@blah", OleDbType.LongVarChar, -1).Value = "very big string";
In your parseResponse()
you are creating a new instance of the BusinessAdapter
class, but you aren't actually using it anywhere, so your RecyclerView
doesn't know the new instance exists.
You either need to:
recyclerView.setAdapter(mBusinessAdapter)
again to update the RecyclerView's adapter reference to point to your new onemBusinessAdapter = new BusinessAdapter(mBusinesses);
to continue using the existing adapter. Since you haven't changed the mBusinesses
reference, the adapter will still use that array list and should update correctly when you call notifyDataSetChanged()
.You can do this all in the File.open block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open playlist_name, 'w' do |f|
music.each do |z|
f.puts z
end
end
Once you start the web installer there's an option to download media, that being the full installation package. There's even download options for what kind of package to download.
I couldn't solve the problem; Then I did the following and the issue was resolved: Refer here:
sudo launchctl unload -w /System/Library/LaunchDaemons/ssh.plist
(Supply your password when it is requested)
sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist
ssh -v localhost
sudo launchctl list | grep "sshd"
46427 - com.openssh.sshd
Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register
parameter, independently of the module used.
Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:
---
- hosts: localhost
tasks:
- shell: ls
register: shell_result
- debug:
var: shell_result.stdout_lines
Here register
tells ansible to save the response of the module into the shell_result
variable, and then we use the debug
module to print the variable out.
An example run would look like the this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
changed: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
"shell_result.stdout_lines": [
"play.yml"
]
}
Responses can contain multiple fields. stdout_lines
is one of the default fields you can expect from a module's response.
Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout
or stdout_lines
values, however the msg
field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.
Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v
, -vvv
and -vvvv
. For example when running the playbook with verbosity (-vvv
) you get this:
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
(...)
changed: [localhost] => {
"changed": true,
"cmd": "ls",
"delta": "0:00:00.007621",
"end": "2017-02-17 23:04:41.912570",
"invocation": {
"module_args": {
"_raw_params": "ls",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
},
"module_name": "command"
},
"rc": 0,
"start": "2017-02-17 23:04:41.904949",
"stderr": "",
"stdout": "play.retry\nplay.yml",
"stdout_lines": [
"play.retry",
"play.yml"
],
"warnings": []
}
As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines
is available, and its contents are what we expect.
To answer your main question about the jenkins_script
module, if you check its documentation, you can see that it returns the output in the output
field, so you might want to try the following:
tasks:
- jenkins_script:
script: (...)
register: jenkins_result
- debug:
var: jenkins_result.output
You can't use Template expression operators(pipe, save navigator) within template statement:
(ngModelChange)="Template statements"
(ngModelChange)="item.value | useMyPipeToFormatThatValue=$event"
https://angular.io/guide/template-syntax#template-statements
Like template expressions, template statements use a language that looks like JavaScript. The template statement parser differs from the template expression parser and specifically supports both basic assignment (=) and chaining expressions (with ; or ,).
However, certain JavaScript syntax is not allowed:
- new
- increment and decrement operators, ++ and --
- operator assignment, such as += and -=
- the bitwise operators | and &
- the template expression operators
So you should write it as follows:
<input [ngModel]="item.value | useMyPipeToFormatThatValue"
(ngModelChange)="item.value=$event" name="inputField" type="text" />
A less orthodox approach might be
SELECT * FROM table_name
WHERE LEFT(table_name.date, 7) = LEFT(CURDATE(), 7)
AND table_name.date <= CURDATE();
as a date being between the first of a month and now is equivalent to a date being in this month, and before now. I do feel that this is a bit easier on the eyes than some other approaches, though.
Trailing whitespace:
It is extra spaces (and tabs) at the end of line
^^^^^ here
Strip them:
#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""
import sys
if len(sys.argv[1:]) != 1:
sys.exit(__doc__)
content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
content = infile.read()
with open(outp, 'wb') as output:
for line in content.splitlines():
newline = line.rstrip(" \t")
outsize += len(newline) + 1
output.write(newline + '\n')
print("Done. Stripped %s bytes." % (len(content)-outsize))
I had the same problem. For me it was that I was using the same my documents as on a previous Windows installation. Simply removing the IISExpress folder from my documents did the trick.
When you'll play enough with LocalBroadcastReceiver I'll suggest you to give Green Robot's EventBus a try - you will definitely realize the difference and usefulness of it compared to LBR. Less code, customizable about receiver's thread (UI/Bg), checking receivers availability, sticky events, events could be used as data delivery etc.
Yes we can change that but with some more attention
Now add this in your build.gradle in your project while make sure you have checked the build variant of your project like release or Debug
so here I have set my build variant as release
but you may select as Debug as well.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig getSigningConfig()
applicationVariants.all { variant ->
variant.outputs.each { output ->
def date = new Date();
def formattedDate = date.format('yyyyMMddHHmmss')
output.outputFile = new File(output.outputFile.parent,
output.outputFile.name.replace("-release", "-" + formattedDate)
//for Debug use output.outputFile = new File(output.outputFile.parent,
// output.outputFile.name.replace("-debug", "-" + formattedDate)
)
}
}
}
}
You may Do it With different Approach Like this
defaultConfig {
applicationId "com.myapp.status"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
setProperty("archivesBaseName", "COMU-$versionName")
}
Using Set property method in build.gradle and Don't forget to sync the gradle before running the projects Hope It will solve your problem :)
A New approach to handle this added recently by google update You may now rename your build according to flavor or Variant output //Below source is from developer android documentation For more details follow the above documentation link
Using the Variant API to manipulate variant outputs is broken with the new plugin. It still works for simple tasks, such as changing the APK name during build time, as shown below:
// If you use each() to iterate through the variant objects,
// you need to start using all(). That's because each() iterates
// through only the objects that already exist during configuration time—
// but those object don't exist at configuration time with the new model.
// However, all() adapts to the new model by picking up object as they are
// added during execution.
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${variant.name}-${variant.versionName}.apk"
}
}
Renaming .aab bundle This is nicely answered by David Medenjak
tasks.whenTaskAdded { task ->
if (task.name.startsWith("bundle")) {
def renameTaskName = "rename${task.name.capitalize()}Aab"
def flavor = task.name.substring("bundle".length()).uncapitalize()
tasks.create(renameTaskName, Copy) {
def path = "${buildDir}/outputs/bundle/${flavor}/"
from(path)
include "app.aab"
destinationDir file("${buildDir}/outputs/renamedBundle/")
rename "app.aab", "${flavor}.aab"
}
task.finalizedBy(renameTaskName)
}
//@credit to David Medenjak for this block of code
}
Is there need of above code
What I have observed in the latest version of the android studio 3.3.1
The rename of .aab bundle is done by the previous code there don't require any task rename at all.
Hope it will help you guys. :)
There are two ways to write case statements, you seem to be using a combination of the two
case a.updatedDate
when 1760 then 'Entered on' + a.updatedDate
when 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end
or
case
when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end
are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.
I ran into this recently. Our organization restricts the accounts that run application pools to a select list of servers in Active Directory. I found that I had not added one of the machines hosting the application to the "Log On To" list for the account in AD.
It can be changed in the $CATALINA_BASE/conf/server.xml
in the <Host />
. See the Tomcat documentation, specifically the section in regards to the Host container:
The default is webapps
relative to the $CATALINA_BASE
. An absolute pathname can be used.
Hope that helps.
Actually you can do with VS Code the following:
Try an OutputStream
or more specifically FileOutputStream
I have a set of 15 subroutines I add to every Coded Excel Workbook I create and this is one of them. The following routine clears the area and creates a border.
Sample Call:
Call BoxIt(Range("A1:z25"))
Subroutine:
Sub BoxIt(aRng As Range)
On Error Resume Next
With aRng
'Clear existing
.Borders.LineStyle = xlNone
'Apply new borders
.BorderAround xlContinuous, xlThick, 0
With .Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = 0
.Weight = xlMedium
End With
With .Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = 0
.Weight = xlMedium
End With
End With
End Sub
For ASP.NET Core (tested using 2.0+ and 3.0), if you prefer to read the source documentation: https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/README.md
Otherwise following these 4 steps works:
Install AutoMapper.Extensions.Microsoft.DependancyInjection from nuget.
Simply add some profile classes.
Then add below to your startup.cs class.
services.AddAutoMapper(OneOfYourProfileClassNamesHere)
Then simply Inject IMapper in your controllers or wherever you need it:
public class EmployeesController {
private readonly IMapper _mapper;
public EmployeesController(IMapper mapper){
_mapper = mapper;
}
And if you want to use ProjectTo its now simply:
var customers = await dbContext.Customers.ProjectTo<CustomerDto>(_mapper.ConfigurationProvider).ToListAsync()
For me, it was permission issue. Docker run is called with a user profile but root is the user inside the container. The solution was to make curl write to /tmp since that has write permission for all users , not just root.
I used the -o option.
-o /tmp/file_to_download
According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData});
Codetoffel answer does work just fine for me though.
You should change the name of the remote repository to something else.
git remote add origin [email protected]:myname/oldrep.git
to
git remote add neworigin [email protected]:myname/oldrep.git
I think this should work.
Yes, these are for repository init and adding a new remote. Just with a change of name.
Name2 is a field. WPF binds only to properties. Change it to:
public string Name2 { get; set; }
Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:
partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string _name2;
public string Name2
{
get { return _name2; }
set
{
if (value != _name2)
{
_name2 = value;
OnPropertyChanged("Name2");
}
}
}
}
You should consider moving this to a separate data object rather than on your Window class.
You can use the following if you want to specify tricky formats:
df['date_col'] = pd.to_datetime(df['date_col'], format='%d/%m/%Y')
More details on format
here:
The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormData
and also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I'm quoting the code snippet for convenience:
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
With the latest update to the extension all you need to do is just specify the "python.pythonPath"
as follows.
The values for "python.autoComplete.extraPaths"
will be determined during runtime, but you are still free to specify custom paths in there.
Please, remember to restart Visual Studio Code once the necessary changes have been made.
{
"editor.rulers": [80,100],
"python.pythonPath":"~/dev/venvs/proj/bin/python"
}
DateTime values should be inserted as if they are strings surrounded by single quotes:
'20100301'
SQL Server allows for many accepted date formats and it should be the case that most development libraries provide a series of classes or functions to insert datetime values properly. However, if you are doing it manually, it is important to distinguish the date format using DateFormat
and to use generalized format:
Set DateFormat MDY --indicates the general format is Month Day Year
Insert Table( DateTImeCol )
Values( '2011-03-12' )
By setting the dateformat, SQL Server now assumes that my format is YYYY-MM-DD
instead of YYYY-DD-MM
.
SQL Server also recognizes a generic format that is always interpreted the same way: YYYYMMDD
e.g. 20110312
.
If you are asking how to insert the current date and time using T-SQL, then I would recommend using the keyword CURRENT_TIMESTAMP
. For example:
Insert Table( DateTimeCol )
Values( CURRENT_TIMESTAMP )
Windows / OS X:
For multi-line selection, Ctrl+Alt+Down / ?+Alt+Shift+Down will extend your selection or cursor position to the next line. Ctrl+Right / ?+Right will move to the end of each line, no matter how long. To escape the multi-line selection, hit Esc.
See the VS Code keybindings (OS sensitive)
System.Environment has WorkingSet- a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context.
If you want a lot of details there is System.Diagnostics.PerformanceCounter, but it will be a bit more effort to setup.
More simple way...:
Dim dt As DataTable = DirectCast(GridView1.DataSource, DataTable)
Dim dv As New DataView(dt)
If GridView1.Attributes("dir") = SortDirection.Ascending Then
dv.Sort = e.SortExpression & " DESC"
GridView1.Attributes("dir") = SortDirection.Descending
Else
GridView1.Attributes("dir") = SortDirection.Ascending
dv.Sort = e.SortExpression & " ASC"
End If
GridView1.DataSource = dv
GridView1.DataBind()
Well there is no direct method to do it You can consider some workarounds.
If you dont need a definite border (clearcut border) then you can depend on shadow for the purpose
[view1 setBackgroundColor:[UIColor blackColor]];
UIColor *color = [UIColor yellowColor];
view1.layer.shadowColor = [color CGColor];
view1.layer.shadowRadius = 10.0f;
view1.layer.shadowOpacity = 1;
view1.layer.shadowOffset = CGSizeZero;
view1.layer.masksToBounds = NO;
Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries..
Create Proc SP1
(
@ID int,
@Name varchar(40)
-- etc parameter list, If you don't have any parameter then no need to pass.
)
AS
BEGIN
-- Here we have some opereations
-- If there is any Error Before Executing SP2 then SP will stop executing.
Exec SP2 @ID,@Name,@SomeID OUTPUT
-- ,etc some other parameter also we can use OutPut parameters like
-- @SomeID is useful for some other operations for condition checking insertion etc.
-- If you have any Error in you SP2 then also it will stop executing.
-- If you want to do any other operation after executing SP2 that we can do here.
END
I fiddled around and came up with this. The idea is that the object has all the Array.prototype methods defined, but executes them on a separate array object. This gives the ability to observe methods like shift(), pop() etc. Although some methods like concat() won't return the OArray object. Overloading those methods won't make the object observable if accessors are used. To achieve the latter, the accessors are defined for each index within given capacity.
Performance wise... OArray is around 10-25 times slower compared to the plain Array object. For the capasity in a range 1 - 100 the difference is 1x-3x.
class OArray {
constructor(capacity, observer) {
var Obj = {};
var Ref = []; // reference object to hold values and apply array methods
if (!observer) observer = function noop() {};
var propertyDescriptors = Object.getOwnPropertyDescriptors(Array.prototype);
Object.keys(propertyDescriptors).forEach(function(property) {
// the property will be binded to Obj, but applied on Ref!
var descriptor = propertyDescriptors[property];
var attributes = {
configurable: descriptor.configurable,
enumerable: descriptor.enumerable,
writable: descriptor.writable,
value: function() {
observer.call({});
return descriptor.value.apply(Ref, arguments);
}
};
// exception to length
if (property === 'length') {
delete attributes.value;
delete attributes.writable;
attributes.get = function() {
return Ref.length
};
attributes.set = function(length) {
Ref.length = length;
};
}
Object.defineProperty(Obj, property, attributes);
});
var indexerProperties = {};
for (var k = 0; k < capacity; k++) {
indexerProperties[k] = {
configurable: true,
get: (function() {
var _i = k;
return function() {
return Ref[_i];
}
})(),
set: (function() {
var _i = k;
return function(value) {
Ref[_i] = value;
observer.call({});
return true;
}
})()
};
}
Object.defineProperties(Obj, indexerProperties);
return Obj;
}
}
Though its very late reply, I have faced this problem of exporting java entites to CSV, EXCEL etc in various projects, Where we need to provide export feature on UI.
I have created my own light weight framework. It works with any Java Beans, You just need to add annotations on fields you want to export to CSV, Excel etc.
There's a far more simpler solution to tackle this.
The reason why you get ValueError: Index contains duplicate entries, cannot reshape
is because, once you unstack "Location
", then the remaining index columns "id
" and "date
" combinations are no longer unique.
You can avoid this by retaining the default index column (row #) and while setting the index using "id
", "date
" and "location
", add it in "append
" mode instead of the default overwrite mode.
So use,
e.set_index(['id', 'date', 'location'], append=True)
Once this is done, your index columns will still have the default index along with the set indexes. And unstack
will work.
Let me know how it works out.
Just to recap (I'm adding this answer quite a distance from the original question):
If these are all valid then the only possible explanation is that the 6Gb is very fragmented - which I think is a little unlikely. You didn't say how PHP is invoked from Apache - mod_php? fpm? Fcgi?
I would start by examining each of the above predicates - particularly the free memory one. How do you know that there's 6Gb free when the error occurs? A more likely cause is that there's a memory leak occurring which you're not spotting.
You've not provided any details of how apache is configured; I'd also have a look at reducing MaxRequestsPerChild and MaxMemFree. (I'm not very familiar with worker apache where this will apply per thread - really you need a limit per process). If you provided the core setting from the apache config then maybe we could make further suggestions.
Unless you are using Ajax extensively, make sure your keepalive time is 2 or less.
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
You can use the struct's pack:
In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'
The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:
In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'
In [13]: struct.pack("B", 1)
Out[13]: '\x01'
This works the same on both python 2 and python 3.
Note: the inverse operation (bytes to int) can be done with unpack.
I want to register here what was my solution for this error which was a simple file not updated to Github.
I have a full stack project, and my files are structured both root directory for backend and client for the frontend (I am using React.js). All came down to the fact that I was mistakenly pushing the client folder only to Github and all my changes which had an error (missing a comma in a object's instance in my index.js) was not updated in the backend side. Since this Heroku fetches all updates from Github Repository, I couldn't access my server and the error persisted. Then all I had to do was to commit and push to the root directory and update all the changes of the project and everything came back to work again.
List<T>
equality does not check them element-by-element. You can use LINQ's SequenceEqual
method for that:
var a = ints1.SequenceEqual(ints2);
To ignore order, use SetEquals
:
var a = new HashSet<int>(ints1).SetEquals(ints2);
This should work, because you are comparing sequences of IDs, which do not contain duplicates. If it does, and you need to take duplicates into account, the way to do it in linear time is to compose a hash-based dictionary of counts, add one for each element of the first sequence, subtract one for each element of the second sequence, and check if the resultant counts are all zeros:
var counts = ints1
.GroupBy(v => v)
.ToDictionary(g => g.Key, g => g.Count());
var ok = true;
foreach (var n in ints2) {
int c;
if (counts.TryGetValue(n, out c)) {
counts[n] = c-1;
} else {
ok = false;
break;
}
}
var res = ok && counts.Values.All(c => c == 0);
Finally, if you are fine with an O(N*LogN)
solution, you can sort the two sequences, and compare them for equality using SequenceEqual
.
I received the same error when cloning an HTML element for use in a form.
(I have a partially complete form, which has a template injected into it, and then the template is modified)
The error was referencing the original field, and not the cloned version.
I couldn't find any methods that would force the form to re-evaluate itself (in the hope it would get rid of any references to the old fields that now don't exist) before running the validation.
In order to get around this issue, I removed the required attribute from the original element and dynamically added it to the cloned field before injecting it into the form. The form now validates the cloned and modified fields correctly.
localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost
they'll be connecting to their computer instead or yours.
To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all
on a command line.
You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.
To run docker daemon on Linux (from CLI), run:
$ sudo service docker start # Ubuntu/Debian
Note: Skip the $
character when copy and pasting.
On RedHat/CentOS, run: sudo systemctl start docker
.
To initialize the "base" filesystem, run:
$ sudo service docker stop
$ sudo rm -rf /var/lib/docker
$ sudo service docker start
or manually like:
$ sudo docker -d --storage-opt dm.basesize=20G
docker-machine
on LinuxTo install machine binaries on Linux:
locally:
install -vm755 <(curl -L https://github.com/docker/machine/releases/download/v0.5.3/docker-machine_linux-amd64) $HOME/bin/docker-machine
global:
sudo bash -c 'install -vm755 <(curl -L https://github.com/docker/machine/releases/download/v0.5.3/docker-machine_linux-amd64) /usr/local/bin/docker-machine'
On macOS the docker
binary is only a client and you cannot use it to run the docker daemon, because Docker daemon uses Linux-specific kernel features, therefore you can’t run Docker natively in OS X. So you have to install docker-machine
in order to create VM and attach to it.
docker-machine
on macOSIf you don't have docker-machine
command yet, install it by using one of the following methods:
brew install docker-machine docker
.manually from GitHub:
install -v <(curl https://github.com/docker/machine/releases/download/v0.5.3/docker-machine_linux-amd64) /usr/local/bin/docker-machine
See: Get started with Docker for Mac.
docker-machine
on macOSTo start Docker Machine via Homebrew, run:
brew services start docker-machine
To create a default
machine (if you don't have one, see: docker-machine ls
):
docker-machine create --driver virtualbox default
Then set-up the environment for the Docker client:
eval "$(docker-machine env default)"
Then double-check by listing containers:
docker ps
See: Get started with Docker Machine and a local VM.
Alternatively to above solution, you can install a Docker app by:
brew cask install docker
Check this post for more details. See also: Cannot connect to the Docker daemon on macOS
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.
Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.
To append 'api'
to my baseURL, I have my default baseURL set as,
axios.defaults.baseURL = '/api/';
Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'
axios({
method:'post',
url:'logout',
baseURL: '/',
})
.then(response => {
window.location.reload();
})
.catch(error => {
console.log(error);
});
With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write
$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi
or, using the more efficient tr
$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd
My problem was with extra </div>
tag inside the first tab.
You can make an AJAX request if the url is in the same domain, e.g., same host different application. If so, I'd probably use a framework like jQuery, most likely the get method.
$.get('http://someurl.com',function(data,status) {
...parse the data...
},'html');
If you run into cross domain issues, then your best bet is to create a server-side action that proxies the request for you. Do your request to your server using AJAX, have the server request and return the response from the external host.
Thanks to@nickf, for pointing out the obvious problem with my original solution if the url is in a different domain.
Explain Python's slice notation
In short, the colons (:
) in subscript notation (subscriptable[subscriptarg]
) make slice notation - which has the optional arguments, start
, stop
, step
:
sliceable[start:stop:step]
Python slicing is a computationally fast way to methodically access parts of your data. In my opinion, to be even an intermediate Python programmer, it's one aspect of the language that it is necessary to be familiar with.
To begin with, let's define a few terms:
start: the beginning index of the slice, it will include the element at this index unless it is the same as stop, defaults to 0, i.e. the first index. If it's negative, it means to start
n
items from the end.stop: the ending index of the slice, it does not include the element at this index, defaults to length of the sequence being sliced, that is, up to and including the end.
step: the amount by which the index increases, defaults to 1. If it's negative, you're slicing over the iterable in reverse.
You can make any of these positive or negative numbers. The meaning of the positive numbers is straightforward, but for negative numbers, just like indexes in Python, you count backwards from the end for the start and stop, and for the step, you simply decrement your index. This example is from the documentation's tutorial, but I've modified it slightly to indicate which item in a sequence each index references:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
To use slice notation with a sequence that supports it, you must include at least one colon in the square brackets that follow the sequence (which actually implement the __getitem__
method of the sequence, according to the Python data model.)
Slice notation works like this:
sequence[start:stop:step]
And recall that there are defaults for start, stop, and step, so to access the defaults, simply leave out the argument.
Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:
my_list[-9:]
When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")
The full notation is
my_list[-9:None:None]
and to substitute the defaults (actually when step
is negative, stop
's default is -len(my_list) - 1
, so None
for stop really just means it goes to whichever end step takes it to):
my_list[-9:len(my_list):1]
The colon, :
, is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of making a shallow copy of lists in Python 2 is
list_copy = sequence[:]
And clearing them is with:
del my_list[:]
(Python 3 gets a list.copy
and list.clear
method.)
step
is negative, the defaults for start
and stop
changeBy default, when the step
argument is empty (or None
), it is assigned to +1
.
But you can pass in a negative integer, and the list (or most other standard slicables) will be sliced from the end to the beginning.
Thus a negative slice will change the defaults for start
and stop
!
I like to encourage users to read the source as well as the documentation. The source code for slice objects and this logic is found here. First we determine if step
is negative:
step_is_negative = step_sign < 0;
If so, the lower bound is -1
meaning we slice all the way up to and including the beginning, and the upper bound is the length minus 1, meaning we start at the end. (Note that the semantics of this -1
is different from a -1
that users may pass indexes in Python indicating the last item.)
if (step_is_negative) { lower = PyLong_FromLong(-1L); if (lower == NULL) goto error; upper = PyNumber_Add(length, lower); if (upper == NULL) goto error; }
Otherwise step
is positive, and the lower bound will be zero and the upper bound (which we go up to but not including) the length of the sliced list.
else { lower = _PyLong_Zero; Py_INCREF(lower); upper = length; Py_INCREF(upper); }
Then, we may need to apply the defaults for start
and stop
- the default then for start
is calculated as the upper bound when step
is negative:
if (self->start == Py_None) { start = step_is_negative ? upper : lower; Py_INCREF(start); }
and stop
, the lower bound:
if (self->stop == Py_None) { stop = step_is_negative ? lower : upper; Py_INCREF(stop); }
You may find it useful to separate forming the slice from passing it to the list.__getitem__
method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.
However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:
last_nine_slice = slice(-9, None)
The second argument, None
, is required, so that the first argument is interpreted as the start
argument otherwise it would be the stop
argument.
You can then pass the slice object to your sequence:
>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]
It's interesting that ranges also take slices:
>>> range(100)[last_nine_slice]
range(91, 100)
Since slices of Python lists create new objects in memory, another important function to be aware of is itertools.islice
. Typically you'll want to iterate over a slice, not just have it created statically in memory. islice
is perfect for this. A caveat, it doesn't support negative arguments to start
, stop
, or step
, so if that's an issue you may need to calculate indices or reverse the iterable in advance.
length = 100
last_nine_iter = itertools.islice(list(range(length)), length-9, None, 1)
list_last_nine = list(last_nine_iter)
and now:
>>> list_last_nine
[91, 92, 93, 94, 95, 96, 97, 98, 99]
The fact that list slices make a copy is a feature of lists themselves. If you're slicing advanced objects like a Pandas DataFrame, it may return a view on the original, and not a copy.
Put in addresses this code:
objMessage.To.Add(***addresses:=***"[email protected] , [email protected] , [email protected]")
If you are using WAMP on you local computer (mysql version 5.7.14) Step 1: open my.ini file Step 2: un-comment this line 'skip-grant-tables' by removing the semi-colon step 3: restart mysql server step 4: launch mySQL console step 5:
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
Step 6: Problem solved!!!!
Another option is to use the csvsql command from the csvkit library.
Example usage directly on command line:
csvsql --db mysql:///test --tables yourtable --insert yourfile.csv
This can be executed directly on the command line, or built into a python or shell script for automation if you need to do this for a number of files.
csvsql allows you to create database tables on the fly based on the structure of your csv, so it is a lite-code way of getting the first row of your csv to automagically be cast as the MySQL table header.
Full documentation and further examples here: https://csvkit.readthedocs.io/en/1.0.3/scripts/csvsql.html
Elements that are floated are taken out of the normal flow layout, and block elements, such as DIV's, no longer span the width of their parent. The rules change in this situation. Instead of reinventing the wheel, check out this site for some possible solutions to create the two column layout you are after: http://www.maxdesign.com.au/presentation/page_layouts/
Specifically, the "Liquid Two-Column layout".
Cheers!
i have a solution for dynamically created variable value and combined all value in a variable.
if($_SERVER['REQUEST_METHOD']=='POST'){
$r=0;
for($i=1; $i<=4; $i++){
$a = $_POST['a'.$i];
$r .= $a;
}
echo $r;
}
Since Google updates sometimes the name of fixed object properties, the best practice is to use GMaps V3 methods to get coordinates event.overlay.getPath().getArray() and to get lat latlng.lat() and lng latlng.lng().
So, I just wanted to improve this answer a bit exemplifying with polygon and POSTGIS insert case scenario:
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var str_input ='POLYGON((';
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
console.log('polygon path array', event.overlay.getPath().getArray());
$.each(event.overlay.getPath().getArray(), function(key, latlng){
var lat = latlng.lat();
var lon = latlng.lng();
console.log(lat, lon);
str_input += lat +' '+ lon +',';
});
}
str_input = str_input.substr(0,str_input.length-1) + '))';
console.log('the str_input will be:', str_input);
// YOU CAN THEN USE THE str_inputs AS IN THIS EXAMPLE OF POSTGIS POLYGON INSERT
// INSERT INTO your_table (the_geom, name) VALUES (ST_GeomFromText(str_input, 4326), 'Test')
});
When Excel finds mixed data types in same column it guesses what is the right format for the column (the majority of the values determines the type of the column) and dismisses all other values by inserting NULLs. But Excel does it far badly (e.g. if a column is considered text and Excel finds a number then decides that the number is a mistake and insert a NULL instead, or if some cells containing numbers are "text" formatted, one may get NULL values into an integer column of the database).
Solution:
Note that formatting the columns on an existing Excel sheet is not enough.
Try this:
// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg),
Base64.NO_WRAP);
Use a profiler (JProfiler, Netbeans Profiler, Visual VM, Eclipse Profiler, etc). You'll get the most accurate results and is the least intrusive. They use the built-in JVM mechanism for profiling which can also give you extra information like stack traces, execution paths, and more comprehensive results if necessary.
When using a fully integrated profiler, it's faily trivial to profile a method. Right click, Profiler -> Add to Root Methods. Then run the profiler just like you were doing a test run or debugger.
Create below class in base class. Class To get all controls:
public static class ControlExtensions
{
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
}
From Database: Get All Actions IDs (like divAction1,divAction2 ....) dynamic in DATASET (DTActions) allow on specific User.
In Aspx: in HTML Put Action(button,anchor etc) in div or span and give them id like
<div id="divAction1" visible="false" runat="server" clientidmode="Static">
<a id="anchorAction" runat="server">Submit
</a>
</div>
IN CS: Use this function on your page:
private void ShowHideActions()
{
var controls = Page.GetAllControlsOfType<HtmlGenericControl>();
foreach (DataRow dr in DTActions.Rows)
{
foreach (Control cont in controls)
{
if (cont.ClientID == "divAction" + dr["ActionID"].ToString())
{
cont.Visible = true;
}
}
}
}
you can try also doing this
sleep (50000);
cout << "any text" << endl;
This will hold your code for 50000m, then prints message and closes. But please keep in mind that it will not pause forever.
The logged error does say that port 3820 is the problem, but I would suggest investigating all the ports that your app is trying to listen on. I ran into this problem and the issue was a port that I'd forgotten about - not the "main" one that I was looking for.
In addition to the answer posted by Tim Banks, which followed to solving my issue I had to edit one simple thing.
Someone else might have the same issue; I'm working with a Bootstrap dropdown in a dropdown. But the text can be wider as the current content at this point (and there aren't many good ways to resolve that through css).
I used:
$table.css({ position: "absolute", visibility: "hidden", display: "table" });
instead, which sets the container to a table which always scales in width if the contents are wider.
Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.
Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.
//
// ViewController.m
// AutoLayoutDynamicVerticalContainerHeight
//
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end
@implementation ViewController
- (void)viewDidLoad
{
// INVOKE SUPER
[super viewDidLoad];
// INIT ALL REQUIRED UI ELEMENTS
self.contentView = [[UIView alloc] init];
self.myLabel = [[UILabel alloc] init];
self.myOtherLabel = [[UILabel alloc] init];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);
// TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;
// ESTABLISH VIEW HIERARCHY
[self.view addSubview:self.contentView]; // View adds content view
[self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
[self.contentView addSubview:self.myOtherLabel];
// LAYOUT
// Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
// Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet
/* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
// ^To me this is what's weird... but okay once you understand...
// Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
// Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
// Note, this is the view that we are choosing to use to drive the height (and width) of our container...
// The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];
// Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];
// COLOR VIEWS
self.view.backgroundColor = [UIColor purpleColor];
self.contentView.backgroundColor = [UIColor redColor];
self.myLabel.backgroundColor = [UIColor orangeColor];
self.myOtherLabel.backgroundColor = [UIColor greenColor];
// CONFIGURE VIEWS
// Configure MY LABEL
self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
self.myLabel.numberOfLines = 0; // Let it flow
// Configure MY OTHER LABEL
self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
self.myOtherLabel.numberOfLines = 0;
self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}
@end
If your (logical) check is for a negation (!) and you want to capture both JS null
and undefined
(as different Browsers will give you different results) you would use the less restrictive comparison:
e.g.:
var ItemID = Item.get_id();
if (ItemID != null)
{
//do stuff
}
This will capture both null
and undefined
It is because you forgot to pass in event
into the click
function:
$('.menuOption').on('click', function (e) { // <-- the "e" for event
e.preventDefault(); // now it'll work
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
On a side note, e
is more commonly used as opposed to the word event
since Event
is a global variable in most browsers.
with open(filename) as f:
while True:
c = f.read(1)
if not c:
print "End of file"
break
print "Read a character:", c
In your viewDidLoad
:
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
{
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
Put in other words, this error is telling you that SQL Server does not know which B
to select from the group.
Either you want to select one specific value (e.g. the MIN
, SUM
, or AVG
) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B
in the GROUP BY
field list).
Consider the following data:
ID A B 1 1 13 1 1 79 1 2 13 1 2 13 1 2 42
The query
SELECT A, COUNT(B) AS T1
FROM T2
GROUP BY A
would return:
A T1 1 2 2 3
which is all well and good.
However consider the following (illegal) query, which would produce this error:
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A
And its returned data set illustrating the problem:
A T1 B 1 2 13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...? 2 3 13? 42? ...?
However, the following two queries make this clear, and will not cause the error:
Using an aggregate
SELECT A, COUNT(B) AS T1, SUM(B) AS B
FROM T2
GROUP BY A
would return:
A T1 B 1 2 92 2 3 68
Adding the column to the GROUP BY
list
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A, B
would return:
A T1 B 1 1 13 1 1 79 2 2 13 2 1 42
I had the same problem. To fix it in Jboss 7 AS, I copy the oracle driver jar file to Jboss module folder. Example: ../jboss-as-7.1.1.Final/modules/org/hibernate/main
.
You also need to change "module.xml"
<module xmlns="urn:jboss:module:1.1" name="org.hibernate">
<resources>
<resource-root path="hibernate-core-4.0.1.Final.jar"/>
<resource-root path="hibernate-commons-annotations-4.0.1.Final.jar"/>
<resource-root path="hibernate-entitymanager-4.0.1.Final.jar"/>
<resource-root path="hibernate-infinispan-4.0.1.Final.jar"/>
<resource-root path="ojdbc6.jar"/>
</resources>
<dependencies>
<module name="asm.asm"/>
<module name="javax.api"/>
<module name="javax.persistence.api"/>
<module name="javax.transaction.api"/>
<module name="javax.validation.api"/>
<module name="org.antlr"/>
<module name="org.apache.commons.collections"/>
<module name="org.dom4j"/>
<module name="org.infinispan" optional="true"/>
<module name="org.javassist"/>
<module name="org.jboss.as.jpa.hibernate" slot="4" optional="true"/>
<module name="org.jboss.logging"/>
<module name="org.hibernate.envers" services="import" optional="true"/>
</dependencies>
You can just capture the output and pass it through a filter, something like:
mysql show processlist
| grep -v '^\+\-\-'
| grep -v '^| Id'
| sort -n -k12
The two greps strip out the header and trailer lines (others may be needed if there are other lines not containing useful information) and the sort is done based on the numeric field number 12 (I think that's right).
This one works for your immediate output:
mysql show processlist
| grep -v '^\+\-\-'
| grep -v '^| Id'
| grep -v '^[0-9][0-9]* rows in set '
| grep -v '^ '
| sort -n -k12
One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.
In my case I was throwing Exception
on a namespaced file, so php tried to catch My\Namespace\Exception
therefore not catching any exceptions at all.
Worth checking if catch (Exception $e)
is finding the right Exception
class.
Just try catch (\Exception $e)
(with that \
there) and see if it works.
Ok so if you need 72dp, couldn't you just add the difference in padding in the xml file? This way you keep Androids default Inset/Padding that they want us to use.
So: 72-16=56
Therefor: add 56dp padding to put yourself at an indent/margin total of 72dp.
Or you could just change the values in the Dimen.xml files. that's what I am doing now. It changes everything, the entire layout, including the ToolBar when implemented in the new proper Android way.
The link I added shows the Dimen values at 2dp because I changed it but it was default set at 16dp. Just FYI...
Did you set the section header height in the viewDidLoad?
self.tableView.sectionHeaderHeight = 70
Plus you should replace
self.view.addSubview(view)
by
view.addSubview(label)
Finally you have to check your frames
let view = UIView(frame: CGRect.zeroRect)
and eventually the desired text color as it seems to be currently white on white.
This worked for me.
header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow(i for i in header)
for j in some_list:
writer.writerow(j)
Since pandas 0.22 update, comparison options are available like:
and many more. These functions return boolean array. Let's see how we can use them:
# sample data
df = pd.DataFrame({'col1': [0, 1, 2,3,4,5], 'col2': [10, 11, 12,13,14,15]})
# get values from col1 greater than or equals to 1
df.loc[df['col1'].ge(1),'col1']
1 1
2 2
3 3
4 4
5 5
# where co11 values is better 0 and 2
df.loc[df['col1'].between(0,2)]
col1 col2
0 0 10
1 1 11
2 2 12
# where col1 > 1
df.loc[df['col1'].gt(1)]
col1 col2
2 2 12
3 3 13
4 4 14
5 5 15
From the dplyr
package you can also use the mutate_all()
function in combination with toupper()
. This will affect both character and factor classes.
library(dplyr)
df <- mutate_all(df, funs=toupper)
In my case, im getting the similar exception when trying to checkout the project from SVN repo it is prompting for the username and password and i was giving the wrong username every time, when i gave the correct username and password its started working fine..... Such a simple and Hardstopping message.....
Assuming, as seems to be the case, ${triningIdArray}
is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:
var traingIds = ${triningIdArray};
not
var traingIds = "${triningIdArray}";
If you want a formula to do it then:
=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)
This will do it. Change `"WORD" To the word you want.
Rather than use "d", why not "p". I am not sure if the "p *" will work. I didn't try that. You can; however use the following script"
#!/bin/bash
#
MAIL_INDEX=$(printf 'h a\nq\n' | mail | egrep -o '[0-9]* unread' | awk '{print $1}')
markAllRead=
for (( i=1; i<=$MAIL_INDEX; i++ ))
do
markAllRead=$markAllRead"p $i\n"
done
markAllRead=$markAllRead"q\n"
printf "$markAllRead" | mail
Check Opacity, You can set this css property to the div, the <p>
or using <span>
you want to make transparent
And by the way, the font tag is deprecated, use css to style the text
div {
opacity: 0.5;
}
Edit: This code will make the whole element transparent, if you want to make ** just the text ** transparent check @Mattias Buelens answer
Had a similar problem when starting apache jmeter on windows 8 64 bit:
[]apache-jmeter-2.13\bin>jmeter
java.util.prefs.WindowsPreferences <init>
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
Successfully used Dennis Traub solution, with Mkorsch explanations. Or you can create a file with the extension "reg" and write into it the following:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Prefs]
... then execute it.
I got a solution that plays nice with bodyParser, using the verify
callback in bodyParser. In this code, I am using it to get a sha1 of the content and also getting the raw body.
app.use(bodyParser.json({
verify: function(req, res, buf, encoding) {
// sha1 content
var hash = crypto.createHash('sha1');
hash.update(buf);
req.hasha = hash.digest('hex');
console.log("hash", req.hasha);
// get rawBody
req.rawBody = buf.toString();
console.log("rawBody", req.rawBody);
}
}));
I am new in Node.js and express.js (started yesterday, literally!) so I'd like to hear comments on this solution.
Dates in VBA are just floating point numbers, where the integer part represents the date and the fraction part represents the time. So in addition to using the Date
function as tlayton says (to get the current date) you can also cast a date value to a integer to get the date-part from an arbitrary date: Int(myDateValue)
.
By the way, one other possibility is that you do have a too old version of cordova android platform.
Error: Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.
Then:
cordova platform update android --save
Apache on Ubuntu, using the Apache plugin:
sudo certbot certonly --cert-name example.com -d m.example.com,www.m.example.com
The above command is vividly explained in the Certbot user guide on changing a certificate's domain names. Note that the command for changing a certificate's domain names applies to adding new domain names as well.
Edit
If running the above command gives you the error message
Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA.
I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.
I think this is a bit cleaner pure CSS solution than Rens de Nobel's solution. Also this does not prevent from closing the dialog by clicking outside of it.
http://plnkr.co/edit/JCGVZQ?p=preview
Just add some CSS class to DIV container with .modal-dialog class to gain higher specificity than the bootstraps CSS, e.g. .centered.
HTML
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog centered modal-lg">
<div class="modal-content">
...
</div>
</div>
</div>
And make this .modal-dialog.centered container fixed and properly positioned.
CSS
.modal .modal-dialog.centered {
position: fixed;
bottom: 50%;
right: 50%;
transform: translate(50%, 50%);
}
Or even simpler using flexbox.
CSS
.modal {
display: flex;
align-items: center;
justify-content: center;
}
Best way to do this:
function isNumber(num) {
return (typeof num == 'string' || typeof num == 'number') && !isNaN(num - 0) && num !== '';
};
This satisfies the following test cases:
assertEquals("ISNUMBER-True: 0", true, isNumber(0));
assertEquals("ISNUMBER-True: 1", true, isNumber(-1));
assertEquals("ISNUMBER-True: 2", true, isNumber(-500));
assertEquals("ISNUMBER-True: 3", true, isNumber(15000));
assertEquals("ISNUMBER-True: 4", true, isNumber(0.35));
assertEquals("ISNUMBER-True: 5", true, isNumber(-10.35));
assertEquals("ISNUMBER-True: 6", true, isNumber(2.534e25));
assertEquals("ISNUMBER-True: 7", true, isNumber('2.534e25'));
assertEquals("ISNUMBER-True: 8", true, isNumber('52334'));
assertEquals("ISNUMBER-True: 9", true, isNumber('-234'));
assertEquals("ISNUMBER-False: 0", false, isNumber(NaN));
assertEquals("ISNUMBER-False: 1", false, isNumber({}));
assertEquals("ISNUMBER-False: 2", false, isNumber([]));
assertEquals("ISNUMBER-False: 3", false, isNumber(''));
assertEquals("ISNUMBER-False: 4", false, isNumber('one'));
assertEquals("ISNUMBER-False: 5", false, isNumber(true));
assertEquals("ISNUMBER-False: 6", false, isNumber(false));
assertEquals("ISNUMBER-False: 7", false, isNumber());
assertEquals("ISNUMBER-False: 8", false, isNumber(undefined));
assertEquals("ISNUMBER-False: 9", false, isNumber(null));
This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.
I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.
You should add the ngDefaultControl attribute to your input like this:
<md-input
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
class="col-sm-4"
(blur)="addRecipient(recipient)"
ngDefaultControl>
</md-input>
Taken from comments in this post:
angular2 rc.5 custom input, No value accessor for form control with unspecified name
Note: For later versions of @angular/material:
Nowadays you should instead write:
<md-input-container>
<input
mdInput
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
(blur)="addRecipient(recipient)">
</md-input-container>
Using Excel 2010 x64
. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:
Swap the data columns, to end with X_data in column A and Y_data in column B.
My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me:
an Excel XY plot literally wants {x,y}
pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away.
For me an XY plot means Y=f(X)
plotted.
In Rails, you can do:
Dir[Rails.root.join('lib', 'ext', '*.rb')].each { |file| require file }
Update: Corrected with suggestion of @Jiggneshh Gohel to remove slashes.
Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...
create or replace procedure temp_proc is
begin
DBMS_OUTPUT.ENABLE(1000000);
DBMS_OUTPUT.PUT_LINE('Test');
end;
...and call it in a PLSQL block...
begin
temp_proc;
end;
...as SQL is non-procedural.
Can also see here on how to turn on MSDTC from the Control Panel's services.msc.
On the server where the trigger resides, you need to turn the MSDTC service on. You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES. Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.
You should override the inspect
method of your object to return the desired hash, or just implement a similar method without overriding the default object behaviour.
If you want to get fancier, you can iterate over an object's instance variables with object.instance_variables
To restate your problem in a way that's easier to express as a regular expression:
Get the substring of characters that is contained between zero or one leading double-quotes and zero or one trailing double-quotes.
Here's the regexp that does that:
var regexp = /^"?(.+?)"?$/;
var newStr = str.replace(/^"?(.+?)"?$/,'$1');
Breaking down the regexp:
^"?
a greedy match for zero or one leading double-quotes"?$
a greedy match for zero or one trailing double-quotes(.+?)
, which will contain the target as $1
.This will return delimited "string" here
for:
str = "delimited "string" here" // ...
str = '"delimited "string" here"' // ...
str = 'delimited "string" here"' // ... and
str = '"delimited "string" here'
You can also use the latest
keyword to install the most recent version available:
"dependencies": {
"fontawesome": "latest"
}
Here is sample of raw pointer iterator.
You shouldn't use iterator class to work with raw pointers!
#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <assert.h>
template<typename T>
class ptr_iterator
: public std::iterator<std::forward_iterator_tag, T>
{
typedef ptr_iterator<T> iterator;
pointer pos_;
public:
ptr_iterator() : pos_(nullptr) {}
ptr_iterator(T* v) : pos_(v) {}
~ptr_iterator() {}
iterator operator++(int) /* postfix */ { return pos_++; }
iterator& operator++() /* prefix */ { ++pos_; return *this; }
reference operator* () const { return *pos_; }
pointer operator->() const { return pos_; }
iterator operator+ (difference_type v) const { return pos_ + v; }
bool operator==(const iterator& rhs) const { return pos_ == rhs.pos_; }
bool operator!=(const iterator& rhs) const { return pos_ != rhs.pos_; }
};
template<typename T>
ptr_iterator<T> begin(T *val) { return ptr_iterator<T>(val); }
template<typename T, typename Tsize>
ptr_iterator<T> end(T *val, Tsize size) { return ptr_iterator<T>(val) + size; }
Raw pointer range based loop workaround. Please, correct me, if there is better way to make range based loop from raw pointer.
template<typename T>
class ptr_range
{
T* begin_;
T* end_;
public:
ptr_range(T* ptr, size_t length) : begin_(ptr), end_(ptr + length) { assert(begin_ <= end_); }
T* begin() const { return begin_; }
T* end() const { return end_; }
};
template<typename T>
ptr_range<T> range(T* ptr, size_t length) { return ptr_range<T>(ptr, length); }
And simple test
void DoIteratorTest()
{
const static size_t size = 10;
uint8_t *data = new uint8_t[size];
{
// Only for iterator test
uint8_t n = '0';
auto first = begin(data);
auto last = end(data, size);
for (auto it = first; it != last; ++it)
{
*it = n++;
}
// It's prefer to use the following way:
for (const auto& n : range(data, size))
{
std::cout << " char: " << static_cast<char>(n) << std::endl;
}
}
{
// Only for iterator test
ptr_iterator<uint8_t> first(data);
ptr_iterator<uint8_t> last(first + size);
std::vector<uint8_t> v1(first, last);
// It's prefer to use the following way:
std::vector<uint8_t> v2(data, data + size);
}
{
std::list<std::vector<uint8_t>> queue_;
queue_.emplace_back(begin(data), end(data, size));
queue_.emplace_back(data, data + size);
}
}
You can use the "instanceof" operator to determine if an object is an instance of a certain class or not. If you do not know the name of an object's type, you can use its constructor property. The constructor property of objects, is a reference to the function that is used to initialize them. Example:
function Circle (x,y,radius) {
this._x = x;
this._y = y;
this._radius = raduius;
}
var c1 = new Circle(10,20,5);
Now c1.constructor is a reference to the Circle()
function.
You can alsow use the typeof
operator, but the typeof
operator shows limited information. One solution is to use the toString()
method of the Object global object. For example if you have an object, say myObject, you can use the toString()
method of the global Object to determine the type of the class of myObject. Use this:
Object.prototype.toString.apply(myObject);
Like the others said:
inputString.split('\n') # --> ['Line 1', 'Line 2', 'Line 3']
This is identical to the above, but the string module's functions are deprecated and should be avoided:
import string
string.split(inputString, '\n') # --> ['Line 1', 'Line 2', 'Line 3']
Alternatively, if you want each line to include the break sequence (CR,LF,CRLF), use the splitlines
method with a True
argument:
inputString.splitlines(True) # --> ['Line 1\n', 'Line 2\n', 'Line 3']
Use the collapse
argument to paste
:
paste(a,collapse=" ")
[1] "aa bb cc"
div { margin: auto; }
This will center your div.
Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.
If the column have index and a function is applied on the column then index doesn't work and full table scan occurs, causing really slow query.
Bad Query; This would ignore index on the column date_time
select * from users
where Date(date_time) > '2010-10-10'
To utilize index on column created of type datetime comparing with today/current date, the following method can be used.
Solution for OP:
select * from users
where created > CONCAT(CURDATE(), ' 23:59:59')
Sample to get data for today:
select * from users
where
created >= CONCAT(CURDATE(), ' 00:00:00') AND
created <= CONCAT(CURDATE(), ' 23:59:59')
Or use BETWEEN for short
select * from users
where created BETWEEN
CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59')
Tip: If you have to do a lot of calculation or queries on dates as well as time, then it's very useful to save date and time in separate columns. (Divide & Conquer)
This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.
Problem:
Let say we have document table. Schema as follows schema : document(name,version,auther,modifieddate) composite Keys : name,version
So we need to get latest versions of all documents.
soloution
var result = (from t in Context.document
where ((from tt in Context.document where t.Name == tt.Name
orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
select t).ToList();
If, like me, you have SourceTree installed, but want to use gitk
as well, you can use the version that comes with SourceTree's embedded version of git.
SourceTree's version of git (and thus gitk) is here:
For Windows:
C:\Users\User\AppData\Local\Atlassian\SourceTree\git_local\bin\git.exe
or
%USERPROFILE%\AppData\Local\Atlassian\SourceTree\git_local\bin
For Mac:
/Applications/SourceTree.app/Contents/Resources/git_local/bin
In that directory, you'll find a gitk
executable.
Thanks to @Adrian for the comment which alerted me to this. I thought it was worth posting as an answer in its own right.
I would use the second method as it is more explicit. Otherwise you don't know where the variables are coming from.
Why do you need to check both GET and POST anyway? Surely using one or the other only makes more sense.
This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:
>>> df[condition]
This will return a slice of your dataframe which you can index using iloc
. Here are your examples:
Get first row where A > 3 (returns row 2)
>>> df[df.A > 3].iloc[0]
A 4
B 6
C 3
Name: 2, dtype: int64
If what you actually want is the row number, rather than using iloc
, it would be df[df.A > 3].index[0]
.
Get first row where A > 4 AND B > 3:
>>> df[(df.A > 4) & (df.B > 3)].iloc[0]
A 5
B 4
C 5
Name: 4, dtype: int64
Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)
>>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
A 4
B 6
C 3
Name: 2, dtype: int64
Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:
>>> def series_or_default(X, condition, default_col, ascending=False):
... sliced = X[condition]
... if sliced.shape[0] == 0:
... return X.sort_values(default_col, ascending=ascending).iloc[0]
... return sliced.iloc[0]
>>>
>>> series_or_default(df, df.A > 6, 'A')
A 5
B 4
C 5
Name: 4, dtype: int64
As expected, it returns row 4.
One simple thing you could do is abstract the test inside a function.
local function isempty(s)
return s == nil or s == ''
end
if isempty(foo) then
foo = "default value"
end
Here is an example based on Boost.Preprocessor:
#include <iostream>
#include <boost/preprocessor/punctuation/comma.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/comparison/equal.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/size.hpp>
#include <boost/preprocessor/seq/seq.hpp>
#define DEFINE_ENUM(name, values) \
enum name { \
BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_VALUE, , values) \
}; \
inline const char* format_##name(name val) { \
switch (val) { \
BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_FORMAT, , values) \
default: \
return 0; \
} \
}
#define DEFINE_ENUM_VALUE(r, data, elem) \
BOOST_PP_SEQ_HEAD(elem) \
BOOST_PP_IIF(BOOST_PP_EQUAL(BOOST_PP_SEQ_SIZE(elem), 2), \
= BOOST_PP_SEQ_TAIL(elem), ) \
BOOST_PP_COMMA()
#define DEFINE_ENUM_FORMAT(r, data, elem) \
case BOOST_PP_SEQ_HEAD(elem): \
return BOOST_PP_STRINGIZE(BOOST_PP_SEQ_HEAD(elem));
DEFINE_ENUM(Errors,
((ErrorA)(0))
((ErrorB))
((ErrorC)))
int main() {
std::cout << format_Errors(ErrorB) << std::endl;
}
In new jQuery 1.5 you can use:
$.ajax({
type: "GET",
url: "http://localhost:99000/Services.svc/ReturnPersons",
dataType: "jsonp",
success: readData(data),
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})