Posting this to help someone.
Symptom:
channel 2: open failed: connect failed: Connection refused
debug1: channel 2: free: direct-tcpip:
listening port 8890 for 169.254.76.1 port 8890,
connect from ::1 port 52337 to ::1 port 8890, nchannels 8
My scenario; i had to use the remote server as a bastion host to connect elsewhere. Final Destination/Target: 169.254.76.1, port 8890. Through intermediary server with public ip: ec2-54-162-180-7.compute-1.amazonaws.com
SSH local port forwarding command:
ssh -i ~/keys/dev.tst -vnNT -L :8890:169.254.76.1:8890
[email protected]
What the problem was: There was no service bound on port 8890 in the target host. i had forgotten to start the service.
How did i trouble shoot:
SSH into bastion host and then do curl.
Hope this helps.
You are accesing localhost
, meaning you have a web server running on your machine. To access it from Internet, you need to assign a public IP address to your machine. Then you can access http://<public_ip>:<port>/
. Port number is normally 80.
With only 1 IP you can forget DNS but you can use a MineProxy because the handshake packet of the client contains the host that then he connected to and a MineProxy will ready this host and proxy the connection to a server that is registered for that host
Connect to the Guest and find out the ip address:
ifconfig
example of result (ip address is 10.0.2.15):
eth0 Link encap:Ethernet HWaddr 08:00:27:AE:36:99
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
Go to Vbox instance window -> Menu -> Network adapters:
Go to host system and try it in browser:
http://127.0.0.1:8000
or your network ip address (find out on the host machine by running: ipconfig).
In this case port forwarding is not needed, the communication goes over the LAN back to the host.
On the host machine - find out your netw ip address:
ipconfig
example of result:
IP Address. . . . . . . . . . . . : 192.168.5.1
On the guest machine you can communicate directly with the host, e.g. check it with ping:
# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...
@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):
sudo ufw allow 8000
I've solved it, it can be done executing:
netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33
To remove forwarding:
netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111
Wrap a Missing Filter in the Must-Not section of a Bool Filter. It will only return documents where the field exists, and if you set the "null_value" property to true, values that are explicitly not null.
{
"query":{
"filtered":{
"query":{
"match_all":{}
},
"filter":{
"bool":{
"must":{},
"should":{},
"must_not":{
"missing":{
"field":"field1",
"existence":true,
"null_value":true
}
}
}
}
}
}
}
This code simulates a click on the burguer button to close the navbar by clicking on a link in the menu, keeping the fade out effect. Solution with typescript for angular 7. Avoid routerLink problems.
ToggleNavBar () {
let element: HTMLElement = document.getElementsByClassName( 'navbar-toggler' )[ 0 ] as HTMLElement;
if ( element.getAttribute( 'aria-expanded' ) == 'true' ) {
element.click();
}
}
<li class="nav-item" [routerLinkActive]="['active']">
<a class="nav-link" [routerLink]="['link1']" title="link1" (click)="ToggleNavBar()">link1</a>
</li>
You can use the Java8 syntax for CompletableFuture, this way you can perform additional async computations based on the result from calling an async function.
for example:
CompletableFuture.supplyAsync(this::findSomeData)
.thenApply(this:: intReturningMethod)
.thenAccept(this::notify);
More details can be found in this article
.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):
String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
Also, this came from: Android split not working correctly
Try adding JSON.stringify(result)
to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error
which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.
You can pass it as a normal prop: foo={<ComponentOne />}
For example:
const ComponentOne = () => <div>Hello world!</div>
const ComponentTwo = () => (
<div>
<div>Hola el mundo!</div>
<ComponentThree foo={<ComponentOne />} />
</div>
)
const ComponentThree = ({ foo }) => <div>{foo}</div>
I didn't compile it... but should work (or be close to working).
public static <T> String toString(final List<T> list,
final String delim)
{
final StringBuilder builder;
builder = new StringBuilder();
for(final T item : list)
{
builder.append(item);
builder.append(delim);
}
// kill the last delim
builder.setLength(builder.length() - delim.length());
return (builder.toString());
}
Use keydown
event to do it:
input: HTMLDivElement | null = null;
onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
// 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event
if (event.key === 'Enter') {
event.preventDefault();
event.stopPropagation();
this.onSubmit();
}
}
onSubmit = (): void => {
if (input.textContent) {
this.props.onSubmit(input.textContent);
input.focus();
input.textContent = '';
}
}
render() {
return (
<form className="commentForm">
<input
className="comment-input"
aria-multiline="true"
role="textbox"
contentEditable={true}
onKeyDown={this.onKeyDown}
ref={node => this.input = node}
/>
<button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>
</form>
);
}
On SWIFT 3, you can use:
if let myDouble = NumberFormatter().number(from: yourString)?.doubleValue {
print("My double: \(myDouble)")
}
Note: - If a string contains any characters other than numerical digits or locale-appropriate group or decimal separators, parsing will fail. - Any leading or trailing space separator characters in a string are ignored. For example, the strings “ 5”, “5 ”, and “5” all produce the number 5.
Taken from the documentation: https://developer.apple.com/reference/foundation/numberformatter/1408845-number
Maybe you coul'd use UTF8 bold chars.
For examples: https://yaytext.com/bold-italic/
It works on Chromium 80.0, I don't know on other browsers...
Download Microsoft Account Lockout Tools.
Use LockoutStatus
to find the last DC that didn't pre-authenticate the user that is having issues. Note date and time.
Log into that DC, find that timeframe and check Client Address.
Logoff from those servers.
domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.
loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.
navigate to the folder where you have installed your kibana if you have used yum to install kibana it will be placed in following location by default
/usr/share/kibana
then use the following command
bin/kibana --version
Run this command
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
source ~/.bash_profile
this will solve your problem Reference
For Display any subview to main view,Please use following code
UIViewController *yourCurrentViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (yourCurrentViewController.presentedViewController)
{
yourCurrentViewController = yourCurrentViewController.presentedViewController;
}
[yourCurrentViewController presentViewController:composeViewController animated:YES completion:nil];
For Dismiss any subview from main view,Please use following code
UIViewController *yourCurrentViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (yourCurrentViewController.presentedViewController)
{
yourCurrentViewController = yourCurrentViewController.presentedViewController;
}
[yourCurrentViewController dismissViewControllerAnimated:YES completion:nil];
I had faced same issue whenever I tried executing curl on my https server.
About to connect() to localhost port 443 (#0)
Trying ::1...
Connected to localhost (::1) port 443 (#0)
Initializing NSS with certpath: sql:/etc/pki/nssdb
Observed this issue when I configured keystore path incorrectly. After correcting keystore path it worked.
console.cloud.google.com >> select project >> Networking > VPC network >> firewalls >> create firewall.
To apply the rule to VM instances, select Targets, "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like.
in "Protocols and Ports" enter tcp:9090
Click Save.
This post asks the same question, but for linux - you may find it helpful. Send a ping to each IP on a subnet
nmap is probably the best tool to use, as it can help identify host OS as well as being faster. It is available for the windows platform on the nmap.org site
You can also do this, for readability's sake
boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());
if(!passwordVerified ){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}else{
addNewUser();
}
return passwordVerified;
Instead of checking, just perform the action (web request, mail, ftp, etc.) and be prepared for the request to fail, which you have to do anyway, even if your check was successful.
Consider the following:
1 - check, and it is OK
2 - start to perform action
3 - network goes down
4 - action fails
5 - lot of good your check did
If the network is down your action will fail just as rapidly as a ping, etc.
1 - start to perform action
2 - if the net is down(or goes down) the action will fail
$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.
However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ? Maybe post some code to show what's not working as expected ?
Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!
In simple:
Git - is local repository.
GitHub - is central repository.
If you want to always prune
when you fetch
, I can suggest to use Aliases.
Just type git config -e
to open your editor and change the configuration for a specific project and add a section like
[alias]
pfetch = fetch --prune
the when you fetch with git pfetch
the prune will be done automatically.
I faced the same issue before. I cleared all the IE caches/browsing history/cookies & re-launch IE. It works after caches removed.
You may have a try. :)
Another silly mistake you can do is copy recursive function from non class environment to class and don`t change inner self calls to $this->method_name()
i`m writing this because couldn`t understand why i got this error and this thread is first in google when you search for this error.
CodeIgniter returns result rows as objects, not arrays. From the user guide:
result()
This function returns the query result as an array of objects, or an empty array on failure.
You'll have to access the fields using the following notation:
foreach ($getvidids->result() as $row) {
$vidid = $row->videoid;
}
This code is ill-formed:
int&const icr=i;
Reference: C++17 [dcl.ref]/1:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name or decltype-specifier, in which case the cv-qualifiers are ignored.
This rule has been present in all standardized versions of C++. Because the code is ill-formed:
The compiler should reject the program; and if it doesn't, the executable's behaviour is completely undefined.
NB: Not sure how none of the other answers mentioned this yet... nobody's got access to a compiler?
Use SqlCommand.ExecuteScalar() and cast it to an int
:
cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();
I use the following for my HTML templates:
$(".main").empty();
var _template = '<p id="myelement">Your HTML Code</p>';
var template = $.parseHTML(_template);
var final = $(template).find("#myelement");
$(".main").append(final.html());
Note: Assuming if you are using jQuery
In the web browser, open up developer console (F12 in Chrome and IE), then open network tab and watch the request and response data. Another option - use Fiddler (http://fiddler2.com/).
When you get to see the POST request as it is being sent to your page, look into query string and headers. You will see whether your data comes in query string or as form - or maybe it is not being sent to your page at all.
UPDATE: sorry, had to look at MailGun APIs first, they do not go through your browser, requests come directly from their server. You'll have to debug and examine all members of Request.Params when you get the POST from MailGun.
I know this is old but I found the way to make unload work using Chrome
window.onbeforeunload = function () {
myFunction();
};
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
Here is the workaround:
In eclipse.ini write the following:
-vmargs
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors= org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyHost=*myproxyhost*
-Dhttp.proxyPort=*myproxyport*
-Dhttp.proxyUser=*proxy username*
-Dhttp.proxyPassword=*proxy password*
-Dhttp.nonProxyHosts=localhost|127.0.0.1
After starting eclipse verify, that you use the Manual proxy method.
HTH
I tested both requests-futures and grequests. Grequests is faster but brings monkey patching and additional problems with dependencies. requests-futures is several times slower than grequests. I decided to write my own and simply wrapped requests into ThreadPoolExecutor and it was almost as fast as grequests, but without external dependencies.
import requests
import concurrent.futures
def get_urls():
return ["url1","url2"]
def load_url(url, timeout):
return requests.get(url, timeout = timeout)
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
future_to_url = {executor.submit(load_url, url, 10): url for url in get_urls()}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
resp_err = resp_err + 1
else:
resp_ok = resp_ok + 1
Instructions for Drupal 8 / FontAwesome 5
Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)
Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
$form['keys']['#attributes']['placeholder'][] = t('Search');
$form['actions']['submit']['#value'] = html_entity_decode('');
}
?>
Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.
Make sure you import FontAwesome, add this at the top of the CSS file
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
then add this in the CSS
input#edit-submit {
font-family: 'Font Awesome\ 5 Free';
background-color: transparent;
border: 0;
}
FLUSH ALL CACHES AND IT SHOULD WORK FINE
Add Google Font Effects
If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be
@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
$form['keys']['#attributes']['placeholder'][] = t('Search');
$form['actions']['submit']['#value'] = html_entity_decode('');
$form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>
Perhaps have a look at AquaFold's Aqua Data Studio. It is a database IDE with entity-relationship diagramming. It also includes data profiling. It is not free but its price is very reasonable considering its capabilities.
Stating the obvious, but also make sure you have not silently messed up the reference to the applicationId
in android:authorities
.
In my case I made a typo and omitted the damn dollar sign :
android:authorities="{applicationId}.myprovider"
instead of :
android:authorities="${applicationId}.myprovider"
That did not cause any immediate error (since it is a valid authority name). But a couple days later, when I tried to install different variants of an application, it was a real pain to understand what was wrong, as the error message does not give much info about what is wrong with the content providers.
Another way to troubleshoot this is to compare your merged manifests, looking for identical authorities.
In short, its because of recycling the views and using them again!
how can you avoid that :
1.In onBindViewHolder
check whether you should check or uncheck boxes.
don't forget to put both if and else
if (...)
holder.cbSelect.setChecked(true);
else
holder.cbSelect.setChecked(false);
myItems
array ! so whenever a new view is shown, it read the newest statue of the object.tr
can be more concise for removing characters than sed
or awk
, especially when you want to remove different characters from a string.
Removing double quotes:
echo '"Hi"' | tr -d \"
# Produces Hi without quotes
Removing different kinds of brackets:
echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets
-d
stands for "delete".
Make sure the folder with the standard header files is in the projects path.
I don't know where this is in Turbo C, but I would think there's a way of doing this.
This is offset calculation independent from device. Gets the overlapped height between keyboard and textfield:
func keyboardShown(notification: NSNotification) {
let info = notification.userInfo!
let value: AnyObject = info[UIKeyboardFrameEndUserInfoKey]!
let rawFrame = value.CGRectValue
let keyboardFrame = view.convertRect(rawFrame, fromView: nil)
let screenHeight = UIScreen.mainScreen().bounds.size.height;
let Ylimit = screenHeight - keyboardFrame.size.height
let textboxOriginInSuperview:CGPoint = self.view.convertPoint(CGPointZero, fromCoordinateSpace: lastTextField!)
self.keyboardHeight = (textboxOriginInSuperview.y+self.lastTextField!.frame.size.height) - Ylimit
if(self.keyboardHeight>0){
self.animateViewMoving(true, moveValue: keyboardHeight!)
}else{
keyboardHeight=0
}
}
keyBoardHeight is the offset.
I fear i incur upset reactions but nevertheless, to clarify for me if i'm wrong or those seeing this question and being interested in an answer:
my understanding of https://tools.ietf.org/html/rfc1122 whose status is "an official specification" and as such is the reference for the terminology used in this question and which is neither superseded by another RFC nor has errata contradicting the following:
theoretically, ie. based on the written spec., UDP like given by https://tools.ietf.org/html/rfc1122#section-4 has no "packet size". Thus the answer could be "indefinite"
In practice, which is what this questions likely seeked (and which could be updated for current tech in action), this might be different and I don't know.
I apologize if i caused upsetting. https://tools.ietf.org/html/rfc1122#page-8 The "Internet Protocol Suite" and "Architectural Assumptions" don't make clear to me the "assumption" i was on, based on what I heard, that the layers are separate. Ie. the layer UDP is in does not have to concern itself with the layer IP is in (and the IP layer does have things like Reassembly, EMTU_R, Fragmentation and MMS_R (https://tools.ietf.org/html/rfc1122#page-56))
Make sure these two requirements are satisfied:
Enable annotation processing,
Preferences > Build, Execution, Deployment > Compiler > Annotation Processors > Enable annotation processing
Lombok plugin is installed and enabled for your project.
>>> keyDict = {"a","b","c","d"}
>>> dict([(key, []) for key in keyDict])
Output:
{'a': [], 'c': [], 'b': [], 'd': []}
You can use this
whereDate('date', '=', $date)
If you give whereDate then compare only date from datetime field.
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}
My solution for replacing ${variable} style tokens (inspired by the answers here and by the Spring UriTemplate):
public static String substituteVariables(String template, Map<String, String> variables) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}");
Matcher matcher = pattern.matcher(template);
// StringBuilder cannot be used here because Matcher expects StringBuffer
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
if (variables.containsKey(matcher.group(1))) {
String replacement = variables.get(matcher.group(1));
// quote to work properly with $ and {,} signs
matcher.appendReplacement(buffer, replacement != null ? Matcher.quoteReplacement(replacement) : "null");
}
}
matcher.appendTail(buffer);
return buffer.toString();
}
For Bootstrap 4 simply remove the 'data-ride="carousel"' from the carousel div. This removes auto play at load time.
To enable the auto play again you would still have to use the "play" call in javascript.
you can use 'use' in function like bellow example
function page_properties($objPortal) use($objPage){
$objPage->set_page_title($myrow['title']);
}
I gave up and inserted a simple jQuery code as below. This will add a tr after every tr, if you have so many trs like me. Demo: https://jsfiddle.net/acf9sph6/
<table>
<tbody>
<tr class="my-tr">
<td>one line</td>
</tr>
<tr class="my-tr">
<td>one line</td>
</tr>
<tr class="my-tr">
<td>one line</td>
</tr>
</tbody>
</table>
<script>
$(function () {
$("tr.my-tr").after('<tr class="tr-spacer"/>');
});
</script>
<style>
.tr-spacer
{
height: 20px;
}
</style>
You can use Take extension method
var array = new byte[] {1, 2, 3, 4};
var firstTwoItems = array.Take(2);
I found that by creating the chart in a separate worksheet any updates will apply. HTH
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
I know this question is old, but there's now a package available called drawnow on GitHub as "python-drawnow". This provides an interface similar to MATLAB's drawnow -- you can easily update a figure.
An example for your use case:
import matplotlib.pyplot as plt
from drawnow import drawnow
def make_fig():
plt.scatter(x, y) # I think you meant this
plt.ion() # enable interactivity
fig = plt.figure() # make a figure
x = list()
y = list()
for i in range(1000):
temp_y = np.random.random()
x.append(i)
y.append(temp_y) # or any arbitrary update to your figure's data
i += 1
drawnow(make_fig)
python-drawnow is a thin wrapper around plt.draw
but provides the ability to confirm (or debug) after figure display.
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
The accepted answer here is problematic, because there is no guarantee that an image will have any sort of interactive shell. For example, the drone/drone image contains on a single command /drone
, and it has an ENTRYPOINT
as well, so this will fail:
$ docker run -it drone/drone sh
FATA[0000] DRONE_HOST is not properly configured
And this will fail:
$ docker run --rm -it --entrypoint sh drone/drone
docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "exec: \"sh\": executable file not found in $PATH".
This is not an uncommon configuration; many minimal images contain only the binaries necessary to support the target service. Fortunately, there are mechanisms for exploring an image filesystem that do not depend on the contents of the image. The easiest is probably the docker export
command, which will export a container filesystem as a tar archive. So, start a container (it does not matter if it fails or not):
$ docker run -it drone/drone sh
FATA[0000] DRONE_HOST is not properly configured
Then use docker export
to export the filesystem to tar
:
$ docker export $(docker ps -lq) | tar tf -
The docker ps -lq
there means "give me the id of the most recent docker container". You could replace that with an explicit container name or id.
This answer is similar to the accepted one, but a bit less convoluted.
L<-list()
for (i in 1:3) {
L<-c(L, list(list(sample(1:3))))
}
If you've exported the environment variable:
export demoPath=/usr/local/demo
you can simply refer to it by name in the makefile
(make
imports all the environment variables you have set):
DEMOPATH = ${demoPath} # Or $(demoPath) if you prefer.
If you've not exported the environment variable, it is not accessible until you do export it, or unless you pass it explicitly on the command line:
make DEMOPATH="${demoPath}" …
If you are using a C shell derivative, substitute setenv demoPath /usr/local/demo
for the export
command.
I just had to uncomment the line in jboss-eap-5.0\jboss-as\server\default\conf\props\jmx-console-users.properties
admin=admin
Thats it. Restart Jboss and I was about to get in to JBOSS JMX. Magically this even fixed the error that I used to get while shutting down Jboss from Eclipse.
There is no REVOKE ALL PRIVILEGES ON ALL VIEWS
, so I ended with:
do $$
DECLARE r record;
begin
for r in select * from pg_views where schemaname = 'myschem'
loop
execute 'revoke all on ' || quote_ident(r.schemaname) ||'.'|| quote_ident(r.viewname) || ' from "XUSER"';
end loop;
end $$;
and usual:
REVOKE ALL PRIVILEGES ON DATABASE mydb FROM "XUSER";
REVOKE ALL PRIVILEGES ON SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA myschem FROM "XUSER";
for the following to succeed:
drop role "XUSER";
Unfortunately: NO.
We're all eagerly awaiting the Java support for extension methods
This should be understood in the context of GitHub forks (where you fork a GitHub repo on GitHub before cloning that fork locally).
upstream
generally refers to the original repo that you have forkeddownstream
” and “upstream
”" for more on upstream
term) origin
is your fork: your own repo on GitHub, clone of the original repo of GitHubFrom the GitHub page:
When a repo is cloned, it has a default remote called
origin
that points to your fork on GitHub, not the original repo it was forked from.
To keep track of the original repo, you need to add another remote namedupstream
git remote add upstream git://github.com/<aUser>/<aRepo.git>
(with aUser/aRepo
the reference for the original creator and repository, that you have forked)
You will use upstream
to fetch from the original repo (in order to keep your local copy in sync with the project you want to contribute to).
git fetch upstream
(git fetch
alone would fetch from origin
by default, which is not what is needed here)
You will use origin
to pull and push since you can contribute to your own repository.
git pull
git push
(again, without parameters, 'origin' is used by default)
You will contribute back to the upstream
repo by making a pull request.
I too had OpenJDK on my Ubuntu machine:
$ java -version
java version "1.7.0_51"
OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.13.04.2)
OpenJDK 64-Bit Server VM (build 24.45-b08, mixed mode)
Replacing OpenJDK with the HotSpot VM works fine:
sudo apt-get autoremove openjdk-7-jre-headless
someClassWithinYourSourceDir.getClass().getResourceAsStream();
SearchView
can be added as actionView
in menu using
app:useActionClass = "android.support.v7.widget.SearchView" .
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="@+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
SearchView.OnQueryTextListener
has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
This is how you can implement abstract methods of the listener.
@Override
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView
.
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App
HTML Answer: If you want to create a HTML button that acts like a link, use the 2 common atributtes for it: and/or action="":
<form action="stackoverflow.com"/>
<button type="submit" value="Submit Form"
OR...
"href" is part of the attribute. It helps direct links:
<a href="stackoverflow.com">Href</a>
jus add two zeroes (00) before your color code you will get the transparent of that color
i have done with simple one line code
actionBar.setTitle(Html.fromHtml("<font color='#ff0000'>ActionBartitle </font>"));
If you want PHP to treat $_GET['select2']
as an array of options just add square brackets to the name of the select element like this: <select name="select2[]" multiple …
Then you can acces the array in your PHP script
<?php
header("Content-Type: text/plain");
foreach ($_GET['select2'] as $selectedOption)
echo $selectedOption."\n";
$_GET
may be substituted by $_POST
depending on the <form method="…"
value.
string[] result = new string[table.Columns.Count];
DataRow dr = table.Rows[0];
for (int i = 0; i < dr.ItemArray.Length; i++)
{
result[i] = dr[i].ToString();
}
foreach (string str in result)
Console.WriteLine(str);
Here's a performance comparison of the two. HTTP is more responsive for request-response of small files, but FTP may be better for large files if tuned properly. FTP used to be generally considered faster. FTP requires a control channel and state be maintained besides the TCP state but HTTP does not. There are 6 packet transfers before data starts transferring in FTP but only 4 in HTTP.
I think a properly tuned TCP layer would have more effect on speed than the difference between application layer protocols. The Sun Blueprint Understanding Tuning TCP has details.
Heres another good comparison of individual characteristics of each protocol.
dex
file is a file that is executed on the Dalvik VM.
Dalvik VM includes several features for performance optimization, verification, and monitoring, one of which is Dalvik Executable (DEX).
Java source code is compiled by the Java compiler into .class
files. Then the dx
(dexer) tool, part of the Android SDK processes the .class
files into a file format called DEX
that contains Dalvik byte code. The dx
tool eliminates all the redundant information that is present in the classes. In DEX
all the classes of the application are packed into one file. The following table provides comparison between code sizes for JVM jar files and the files processed by the dex
tool.
The table compares code sizes for system libraries, web browser applications, and a general purpose application (alarm clock app). In all cases dex tool reduced size of the code by more than 50%.
In standard Java environments each class in Java code results in one .class
file. That means, if the Java source code file has one public class and two anonymous classes, let’s say for event handling, then the java compiler will create total three .class
files.
The compilation step is same on the Android platform, thus resulting in multiple .class
files. But after .class
files are generated, the “dx” tool is used to convert all .class
files into a single .dex
, or Dalvik Executable, file. It is the .dex
file that is executed on the Dalvik VM. The .dex
file has been optimized for memory usage and the design is primarily driven by sharing of data.
You can always use strtotime to minus the number of days from the current date:
$users = Users::where('status_id', 'active')
->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
->get();
$('#user_input, #pass_input, #v_pass_input, #email').bind('keyup', function() {
if(allFilled()) $('#register').removeAttr('disabled');
});
function allFilled() {
var filled = true;
$('body input').each(function() {
if($(this).val() == '') filled = false;
});
return filled;
}
JSFiddle with your code, works :)
Had the same issue. Sorted it by defer loading select2
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js" defer></script>
Something that I saw people using is stringexpression > ''
. This may be not the fastest one, but happens to be one of the shortest.
Tried it on MS SQL as well as on PostgreSQL.
The practical difference is binding strength, which can lead to peculiar behavior if you're not prepared for it:
foo = :foo
bar = nil
a = foo and bar
# => nil
a
# => :foo
a = foo && bar
# => nil
a
# => nil
a = (foo and bar)
# => nil
a
# => nil
(a = foo) && bar
# => nil
a
# => :foo
The same thing works for ||
and or
.
Just to expand on juanchopanza's answer a bit...
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
does this:
i
and set it to 0
.i
to Main.size() - 1
. Since Main
is empty, Main.size()
is 0
, and i
gets set to -1
.Main[-1]
is an out-of-bounds access. Kaboom.It is simple.
Thats it. Hope this helps.
At least on Mountain Lion, Viktor's answer will also remove the character 't' when it is at the end of a line. The following fixes that issue:
sed -i '' -e's/[[:space:]]*$//' "$1"
You can also add 'active' class to the selected item.
$('.dropdown').on( 'click', '.dropdown-menu li a', function() {
var target = $(this).html();
//Adds active class to selected item
$(this).parents('.dropdown-menu').find('li').removeClass('active');
$(this).parent('li').addClass('active');
//Displays selected text on dropdown-toggle button
$(this).parents('.dropdown').find('.dropdown-toggle').html(target + ' <span class="caret"></span>');
});
See the jsfiddle example
The only way that works for me (extracted from here):
chmod a+x name_of_file.bin
Then run it by writing
./name_of_file.bin
If you get a permission error you might have to launch your application with root privileges:
sudo ./name_of_file.bin
I had the error of
No provider for Router
It happens when you try to navigate in any service.ts
this.router.navigate(['/home']);
like codes in services cause that error.
You should handle navigating in your components. for example: at login.component
login().subscribe(
(res) => this.router.navigate(['/home']),
(error: any) => this.handleError(error));
Annoying errors happens when we are newbie :)
Its simple just try: sudo apt-get remove python3.7 or the versions that you want to remove
Like others have mentioned, I think of roles as containers for more granular permissions.
Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.
I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.
Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST
These permissions are relatively static, but the relationship of roles to them may be dynamic.
Example -
@Autowired
RolePermissionsRepository repository;
public void setup(){
String roleName = "ROLE_ADMIN";
List<String> permissions = new ArrayList<String>();
permissions.add("CREATE");
permissions.add("READ");
permissions.add("UPDATE");
permissions.add("DELETE");
repository.save(new RolePermissions(roleName, permissions));
}
You may create APIs to manage the relationship of these permissions to a role.
I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685
To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions
To the best of my understanding, time.clock() has as much precision as your system will allow it.
It works fine for me, but it's a little tricky :)
Now you have settings for this session set (every time you load session it will be logged).
As pointed out, you don't need to. Use the Google AJAX Libraries API, and you get CDN hosting of jQuery for free, as depending on your site assets, jQuery can be one of the larger downloads for users.
libpostal: an open-source library to parse addresses, training with data from OpenStreetMap, OpenAddresses and OpenCage.
https://github.com/openvenues/libpostal (more info about it)
Other tools/services:
http://www.gisgraphy.com Free, open source, and ready to use geocoder and geolocalisation webservices, integrating OpenStreetMap, GeoNames and Quattroshapes.
https://github.com/kodapan/osm-common Library for accessing OpenStreetMap services, parsing and processing data.
SQL Server
does not support CREATE TABLE AS SELECT
.
Use this:
SELECT *
INTO A
FROM myview
or
SELECT TOP 10
*
INTO A
FROM myview
ORDER BY
id
I don't know if there is a better way, but the following describes how I did it with a counter and background worker thread.
private object _lock = new object();
private int _runningThreads = 0;
private int Counter{
get{
lock(_lock)
return _runningThreads;
}
set{
lock(_lock)
_runningThreads = value;
}
}
Now whenever you create a worker thread, increment the counter:
var t = new BackgroundWorker();
// Add RunWorkerCompleted handler
// Start thread
Counter++;
In work completed, decrement the counter:
private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Counter--;
}
Now you can check for the counter anytime to see if any thread is running:
if(Couonter>0){
// Some thread is yet to finish.
}
Get the XML using Ajax call, find the main element, loop through all the element and append data in table.
Sample code
//ajax call to load XML and parse it
$.ajax({
type: 'GET',
url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml', // The file path.
dataType: 'xml',
success: function(xml) {
//find all book tags, loop them and append to table body
$(xml).find('book').each(function() {
// Append new data to the tbody element.
$('#tableBody').append(
'<tr>' +
'<td>' +
$(this).find('author').text() + '</td> ' +
'<td>' +
$(this).find('title').text() + '</td> ' +
'<td>' +
$(this).find('genre').text() + '</td> ' +
'<td>' +
$(this).find('price').text() + '</td> ' +
'<td>' +
$(this).find('description').text() + '</td> ' +
'</tr>');
});
}
});
Fiddle link: https://jsfiddle.net/pn9xs8hf/2/
Add following lines within the body tags.
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files
as needed -->
<script src="js/bootstrap.min.js"></script>
For a Windows console app, you want to use SetConsoleCtrlHandler to handle CTRL+C and CTRL+BREAK.
See here for an example.
if you want to merge empty array with existing new value. You must initialize it first.
$products = array();
//just example
for($brand_id=1;$brand_id<=3;$brand_id++){
array_merge($products,getByBrand($brand_id));
}
// it will create empty array
print_r($a);
//check if array of products is empty
for($brand_id=1;$brand_id<=3;$brand_id++){
if(empty($products)){
$products = getByBrand($brand_id);
}else{
array_merge($products,getByBrand($brand_id));
}
}
// it will create array of products
Hope its help.
save.patch
file to wherever (including binary files).git apply <file>
Note: it diff's the currently staged files too.
$ git diff --binary --staged HEAD > save.patch
$ git reset --hard
$ <transport it>
$ git apply save.patch
For anyone running SQL Server on RDS (AWS), there's a built-in procedure callable in the msdb
database which provides comprehensive information for all backup and restore tasks:
exec msdb.dbo.rds_task_status;
This will give a full rundown of each task, its configuration, details about execution (such as completed percentage and total duration), and a task_info
column which is immensely helpful when trying to figure out what's wrong with a backup or restore.
other solution
$template="-----start-------{Value:This is a test 123}------end-------"
$text="-----start-------Hello World------end-------"
$text | ConvertFrom-String -TemplateContent $template
If you use the jQuery solution it will work on IE8:
jQuery
$(document).ready(function(){
$('#myList li:nth-child(odd)').addClass('alternate');
});
CSS
.alternate {
background: black;
}
If you use the CSS soloution it won't work on IE8:
li:nth-child(odd) {
background: black;
}
Your going to need CURL for that task I'm afraid. Nice easy way to do it here: http://davidwalsh.name/execute-http-post-php-curl
Hope that helps
Using plain old JavaScript worked for me:
document.querySelector('#elementName').click();
1) Run Visual Studio Installer
2) Click More on your Installed version and select Repair
3) Restart
Worked on Visual Studio 2017 Community
You could use tr
, like this:
tr " " .
Example:
# echo "hello world" | tr " " .
hello.world
From man tr
:
DESCRIPTION
Translate, squeeze, and/or delete characters from standard input, writ- ing to standard output.
In your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
If I'm going to be using values()
a lot:
enum Suit {
Hearts, Diamonds, Spades, Clubs;
public static final Suit values[] = values();
}
Meanwhile wherever.java:
Suit suit = Suit.values[ordinal];
If you want the array to be private, be my guest:
private static final Suit values[] = values();
public static Suit get(int ordinal) { return values[ordinal]; }
...
Suit suit = Suit.get(ordinal);
Mind your array bounds.
On Mac OS X 10.9, if you try xcode-select --install
, you will get the following error :
Can't install the software because it is not currently available from the Software Update server.
The solution is to download Command Line Tools (OS X 10.9) directly from Apple website : https://developer.apple.com/downloads/index.action?name=for%20Xcode%20-
You will then be able to install the last version of Command Line Tools.
You can just use File.AppendAllText() Method this will solve your problem. This method will take care of File Creation if not available, opening and closing the file.
var outputPath = @"E:\Example.txt";
var data = "Example Data";
File.AppendAllText(outputPath, data);
You can do a printf to anything that is an OutputStream with a PrintStream. Somehow like this, printing into a string stream:
PrintStream ps = new PrintStream(baos);
ps.printf("there is a %s from %d %s", "hello", 3, "friends");
System.out.println(baos.toString());
baos.reset(); //need reset to write new string
ps.printf("there is a %s from %d %s", "flip", 5, "haters");
System.out.println(baos.toString());
baos.reset();
The string stream can be created like this ByteArrayOutputStream:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
If you want to call these methods without including module in another class then you need to define them as module methods:
module UsefulThings
def self.get_file; ...
def self.delete_file; ...
def self.format_text(x); ...
end
and then you can call them with
UsefulThings.format_text("xxx")
or
UsefulThings::format_text("xxx")
But anyway I would recommend that you put just related methods in one module or in one class. If you have problem that you want to include just one method from module then it sounds like a bad code smell and it is not good Ruby style to put unrelated methods together.
I usually read command output in to variables using the FOR
command as it saves having to create temporary files. For example:
FOR /F "usebackq" %i IN (`hostname`) DO SET MYVAR=%i
Note, the above statement will work on the command line but not in a batch file. To use it in batch file escape the %
in the FOR
statement by putting them twice:
FOR /F "usebackq" %%i IN (`hostname`) DO SET MYVAR=%%i
ECHO %MYVAR%
There's a lot more you can do with FOR
. For more details just type HELP FOR
at command prompt.
Heres the code that creates a Dialog which allows the user of your application to change the Look And Feel based on the user's systems. Alternatively, if you can store the wanted Look And Feel's on your application, then they could be "portable", which is the desired result.
public void changeLookAndFeel() {
List<String> lookAndFeelsDisplay = new ArrayList<>();
List<String> lookAndFeelsRealNames = new ArrayList<>();
for (LookAndFeelInfo each : UIManager.getInstalledLookAndFeels()) {
lookAndFeelsDisplay.add(each.getName());
lookAndFeelsRealNames.add(each.getClassName());
}
String changeLook = (String) JOptionPane.showInputDialog(this, "Choose Look and Feel Here:", "Select Look and Feel", JOptionPane.QUESTION_MESSAGE, null, lookAndFeelsDisplay.toArray(), null);
if (changeLook != null) {
for (int i = 0; i < lookAndFeelsDisplay.size(); i++) {
if (changeLook.equals(lookAndFeelsDisplay.get(i))) {
try {
UIManager.setLookAndFeel(lookAndFeelsRealNames.get(i));
break;
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
err.println(ex);
ex.printStackTrace(System.err);
}
}
}
}
}
Write the root logger as below for logging on both console and FILE
log4j.rootLogger=ERROR,console,FILE
And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).
Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:
public static String makeUrl(HttpServletRequest request)
{
return request.getRequestURL().toString() + "?" + request.getQueryString();
}
I don't know about a way to do this with any Spring MVC facilities.
If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
And then use this to get the request bound to the current Thread:
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
I was also running the same problem when I updated to xcode 5 it removed older sdk. But I taken the copy of older SDK from another computer and the same you can download from following link.
http://www.4shared.com/zip/NlPgsxz6/iPhoneOS61sdk.html
(www.4shared.com test account [email protected]/test)
There are 2 ways to work with.
1) Unzip and paste this folder to /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs & restart the xcode.
But this might again removed by Xcode if you update xcode.
2) Another way is Unzip and paste where you want and go to /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs and create a symbolic link here, so that the SDK will remain same even if you update the Xcode.
Another change I made, Build Setting > Architectures > standard (not 64) so list all the versions of Deployment Target
No need to download the zip if you only wanted to change the deployment target.
Here are some screenshots.
Create Parcelable class without plugin in Android Studio
implements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter
and select Add Parcelable implementation
(see image). that's it.
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
Adding on to what has been already answered by Guna Sekaran. Jenkins need the user jenkins to be present in order to run the jenkins as a service.
To add user fire 'useradd jenkins' as root and fire 'passwd jenkins' as root before starting Jenkins as a service.
You don't have to call the external basename
command. Instead, you could use the following commands:
$ s=/the/path/foo.txt
$ echo "${s##*/}"
foo.txt
$ s=${s##*/}
$ echo "${s%.txt}"
foo
$ echo "${s%.*}"
foo
Note that this solution should work in all recent (post 2004) POSIX compliant shells, (e.g. bash
, dash
, ksh
, etc.).
Source: Shell Command Language 2.6.2 Parameter Expansion
More on bash String Manipulations: http://tldp.org/LDP/LG/issue18/bash.html
There is no way to get a position which you really want.
For associative array, to determine last iteration you can use already mentioned counter variable, or determine last item's key first:
end($array);
$last = key($array);
foreach($array as $key => value)
if($key == $last) ....
POST and GET are two HTTP request methods. GET is usually intended to retrieve some data, and is expected to be idempotent (repeating the query does not have any side-effects) and can only send limited amounts of parameter data to the server. GET requests are often cached by default by some browsers if you are not careful.
POST is intended for changing the server state. It carries more data, and repeating the query is allowed (and often expected) to have side-effects such as creating two messages instead of one.
Think I found the correct way to do it using ngx-bootstrap. First import following classes:
import { ViewChild } from '@angular/core';
import { BsModalService, ModalDirective } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
Inside the class implementation of your component add a @ViewCild property, a function to open the modal and do not forget to setup modalService as a private property inside the components class constructor:
@ViewChild('editSomething') editSomethingModal : TemplateRef<any>;
...
modalRef: BsModalRef;
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
...
constructor(
private modalService: BsModalService) { }
The 'editSomething' part of the @ViewChild declaration refers to the component template file and its modal template implementation (#editSomething):
...
<ng-template #editSomething>
<div class="modal-header">
<h4 class="modal-title pull-left">Edit ...</h4>
<button type="button" class="close pull-right" aria-label="Close"
(click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
(click)="modalRef.hide()"
>Close</button>
</div>
</ng-template>
And finaly call the method to open the modal wherever you want like so:
console.log(this.editSomethingModal);
this.openModal( this.editSomethingModal );
this.editSomethingModal is a TemplateRef that could be shown by the ModalService.
Et voila! The modal defined in your component template file is shown by a call from inside your component class implementation. In my case I used this to show a modal from inside an event handler.
The best way to do it is to use the append function:
package main
import (
"fmt"
)
func main() {
x := []int{4, 5, 6, 7, 88}
fmt.Println(x)
x = append(x[:2], x[4:]...)//deletes 6 and 7
fmt.Println(x)
}
If you are using Express or some other framework in the backend , you can add the similar configuration as below and check out the Webpack public path in the configuration, it should work fine even on reload if you are using BrowserRouter
expressApp.get('/*', (request, response) => {
response.sendFile(path.join(__dirname, '../public/index.html'));
});
In powershell :
$this_script_path = $(Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName
$parent_folder = Split-Path $this_script_path -Leaf
gmdate()
is doing exactly what you asked for.
Look at formats here: http://php.net/manual/en/function.gmdate.php
I had the same issue. I changed the application configuration to x86
, then it worked!
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
Case 1 should have worked. I don't see anything wrong. There may be some other problems. I would suggest a clean build.
This is documented in section 3.9.3 of the Spring 3.0 manual:
For a fallback match, the bean name is considered a default qualifier value.
In other words, the default behaviour is as though you'd added @Qualifier("country")
to the setter method.
I ran into this exact problem too. In my case, adding parenthesis around any internal functions (to get them to evaluate first) seemed to do the trick:
Changed
=SUM(A1, SUBSTITUTE(A2,"x","3",1), A3)
to
=SUM(A1, (SUBSTITUTE(A2,"x","3",1)), A3)
If you really want to read through all of the back and forth on this age-old debate, do a search for "natural key" on Stack Overflow. You should get back pages of results.
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)In xCode 11, Swift 5 the \n
works fine, try the below code:
textlabel.numberOfLines = 0
textlabel.text = "This is line one \n This is line two \n This is line three"
++i
is slightly more efficient due to its semantics:
++i; // Fetch i, increment it, and return it
i++; // Fetch i, copy it, increment i, return copy
For int-like indices, the efficiency gain is minimal (if any). For iterators and other heavier-weight objects, avoiding that copy can be a real win (particularly if the loop body doesn't contain much work).
As an example, consider the following loop using a theoretical BigInteger class providing arbitrary precision integers (and thus some sort of vector-like internals):
std::vector<BigInteger> vec;
for (BigInteger i = 0; i < 99999999L; i++) {
vec.push_back(i);
}
That i++ operation includes copy construction (i.e. operator new, digit-by-digit copy) and destruction (operator delete) for a loop that won't do anything more than essentially make one more copy of the index object. Essentially you've doubled the work to be done (and increased memory fragmentation most likely) by simply using the postfix increment where prefix would have been sufficient.
In fact, it is very easy.
composer update
will do all this for you, but it will also update the other packages.
To remove a package without updating the others, specifiy that package in the command, for instance:
composer update monolog/monolog
will remove the monolog/monolog
package.
Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.
For Intellij IDEA Community 2019.1 you will need to follow these steps :
File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
1.
function setColor(e) {
var target = e.target,
count = +target.dataset.count;
target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
target.dataset.count = count === 1 ? 0 : 1;
/*
() : ? - this is conditional (ternary) operator - equals
if (count === 1) {
target.style.backgroundColor = "#7FFF00";
target.dataset.count = 0;
} else {
target.style.backgroundColor = "#FFFFFF";
target.dataset.count = 1;
}
target.dataset - return all "data attributes" for current element,
in the form of object,
and you don't need use global variable in order to save the state 0 or 1
*/
}
<input
type="button"
id="button"
value="button"
style="color:white"
onclick="setColor(event)";
data-count="1"
/>
2.
function setColor(e) {
var target = e.target,
status = e.target.classList.contains('active');
e.target.classList.add(status ? 'inactive' : 'active');
e.target.classList.remove(status ? 'active' : 'inactive');
}
.active {
background-color: #7FFF00;
}
.inactive {
background-color: #FFFFFF;
}
<input
type="button"
id="button"
value="button"
style="color:white"
onclick="setColor(event)"
/>
You can combine strings using stream string like that:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string name = "Bill";
stringstream ss;
ss << "Your name is: " << name;
string info = ss.str();
cout << info << endl;
return 0;
}
1) When the user logs out (Forms signout in Action) I want to redirect to a login page.
public ActionResult Logout() {
//log out the user
return RedirectToAction("Login");
}
2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)
Why would you want to redirect from a controller init?
the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:
public ActionResult Index() {
return RedirectToAction("whateverAction", "whateverController");
}
Inside a GitLab CI pipeline the CI_JOB_TOKEN
environment variable works for me:
git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/...
Source: Gitlab Docs
BTW, setting this variable in .gitlab-ci.yml
helps to debug errors.
variables:
CI_DEBUG_TRACE: "true"
As simple as this:
li = [0, 1, 2, 3]
while 1:
for i, item in enumerate(x):
k = i + 1 if i != len(x) - 1 else 0
print('Current index {} : {}'.format(i,li[k]))
Here's a very simple use case and has nothing to do with thread safety.
To share an object between lambda invocations, the AtomicReference
is an option:
public void doSomethingUsingLambdas() {
AtomicReference<YourObject> yourObjectRef = new AtomicReference<>();
soSomethingThatTakesALambda(() -> {
yourObjectRef.set(youObject);
});
soSomethingElseThatTakesALambda(() -> {
YourObject yourObject = yourObjectRef.get();
});
}
I'm not saying this is good design or anything (it's just a trivial example), but if you have have the case where you need to share an object between lambda invocations, the AtomicReference
is an option.
In fact you can use any object that holds a reference, even a Collection that has only one item. However, the AtomicReference is a perfect fit.
The DOM methods getElementById()
, nextSibling()
, childNodes[n]
, parentNode()
and so on return null
(defined but having no value) when the call does not return a node object.
The property is defined, but the object it refers to does not exist.
This is one of the few times you may not want to test for equality-
if(x!==undefined)
will be true for a null value
but if(x!= undefined)
will be true (only) for values that are not either undefined
or null
.
If you really just want a random value from the available key range, use random.choice
on the dictionary's values (converted to list form, if Python 3).
>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))
You can do that using count
:
my_dict = {i:MyList.count(i) for i in MyList}
>>> print my_dict #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
Or using collections.Counter
:
from collections import Counter
a = dict(Counter(MyList))
>>> print a #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
Instead of writing my own addDays
as suggested by Eli, I would prefer to use DateUtils
from Apache. It is handy especially when you have to use it multiple places in your project.
The API says:
addDays(Date date, int amount)
Adds a number of days to a date returning a new object.
Note that it returns a new Date
object and does not make changes to the previous one itself.
Implement override Equals()
and GetHashCode()
public class CartProduct
{
public Int32 ID;
...
public CartProduct(Int32 ID, ...)
{
this.ID = ID;
...
}
public override int GetHashCode()
{
return ID;
}
public override bool Equals(Object obj)
{
if (obj == null || !(obj is CartProduct))
return false;
else
return GetHashCode() == ((CartProduct)obj).GetHashCode();
}
}
used:
if (CartProducts.Contains(p))
You can try using JavaScript's Date Object
new Date(year,month).getFullYear()%4==0
This will return true or false.
PEP-8 recommends you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'))
or not putting any arguments on the starting line, then indenting to a uniform level:
urlpatterns = patterns(
'',
url(r'^$', listing, name='investment-listing'),
)
urlpatterns = patterns(
'', url(r'^$', listing, name='investment-listing'))
I suggest taking a read through PEP-8 - you can skim through a lot of it, and it's pretty easy to understand, unlike some of the more technical PEPs.
Looks like you might have until the end of 2013 before they officially close it down. http://groups.google.com/group/google-ajax-search-api/browse_thread/thread/6aaa1b3529620610/d70f8eec3684e431?lnk=gst&q=news+api#d70f8eec3684e431
Also, it sounds like they are building a replacement... but it's going to cost you.
I'd say, go to a different service. I think bing has a news API.
You might enjoy (or not) reading: http://news.ycombinator.com/item?id=1864625
This is because you are adding your <tbody>
tag before <td>
in table you cannot print any data without <td>
.
So for that you have to make a <div>
say #header
with position: fixed;
header
{
position: fixed;
}
make another <div>
which will act as <tbody>
tbody
{
overflow:scroll;
}
Now your header is fixed and the body will scroll. And the header will remain there.
When using InfoPlist.strings
file (in XCode it should be placed next to Info.plist
file - real file location can be anywhere within the project probably
) be careful to use the key's short name for the translation.
I was trying to use Privacy - Camera Usage Description
, but the working key is NSCameraUsageDescription
I think ("\") may be causing the problem because \ is the escape character. change it to ("\\")
I also saw this change on my Mac when I went from running pip
to sudo pip
. Adding -H
to sudo causes the message to go away for me. E.g.
sudo -H pip install foo
man sudo
tells me that -H
causes sudo
to set $HOME
to the target users (root in this case).
So it appears pip is looking into $HOME/Library/Log
and sudo
by default isn't setting $HOME
to /root/
. Not surprisingly ~/Library/Log
is owned by you as a user rather than root.
I suspect this is some recent change in pip. I'll run it with sudo -H
for now to work around.
It creates a hidden input on the form for the field (from your model) that you pass it.
It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.
Consider the following ViewModel class:
public class ViewModel
{
public string Value { get; set; }
public int Id { get; set; }
}
Now you want the edit page to store the ID but have it not be seen:
<% using(Html.BeginForm() { %>
<%= Html.HiddenFor(model.Id) %><br />
<%= Html.TextBoxFor(model.Value) %>
<% } %>
This results in the equivalent of the following HTML:
<form name="form1">
<input type="hidden" name="Id">2</input>
<input type="text" name="Value" value="Some Text" />
</form>
Sub TEST()
Dim value1 As String
Dim value2 As String
value1 = ThisWorkbook.Sheets(1).Range("A1").Value 'value from sheet1
value2 = ThisWorkbook.Sheets(2).Range("A1").Value 'value from sheet2
If value1 = value2 Then ThisWorkbook.Sheets(2).Range("L1").Value = value1 'or 2
End Sub
This will compare two sheets cells values and if they match place the value on sheet 2 in column L.
You can wrap the inputs in col-*
classes
<form name="registration_form" id="registration_form" class="form-horizontal">
<div class="form-group">
<div class="col-sm-6">
<label for="firstname" class="sr-only"></label>
<input id="firstname" class="form-control input-group-lg reg_name" type="text" name="firstname" title="Enter first name" placeholder="First name">
</div>
<div class="col-sm-6">
<label for="lastname" class="sr-only"></label>
<input id="lastname" class="form-control input-group-lg reg_name" type="text" name="lastname" title="Enter last name" placeholder="Last name">
</div>
</div><!--/form-group-->
<div class="form-group">
<div class="col-sm-12">
<label for="username" class="sr-only"></label>
<input id="username" class="form-control input-group-lg" type="text" autocapitalize="off" name="username" title="Enter username" placeholder="Username">
</div>
</div><!--/form-group-->
<div class="form-group">
<div class="col-sm-12">
<label for="password" class="sr-only"></label>
<input id="password" class="form-control input-group-lg" type="password" name="password" title="Enter password" placeholder="Password">
</div>
</div><!--/form-group-->
</form>
Some receivers expect EOL sequence, which is typically two characters \r\n
, so try in your code replace the line
unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};
with
unsigned char cmd[] = "INIT\r\n";
BTW, the above way is probably more efficient. There is no need to quote every character.
This is not "wrong" at all, it's just not what the cool guys typically do with MVC. As an aside, I wish some of the early demos of ASP.NET MVC didn't try to cram in Linq-to-Sql at the same time. It's pretty awesome and well suited for MVC, sure, but it's not required. There is nothing about MVC that prevents you from using ADO.NET. For example:
Controller action:
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
DataTable dt = new DataTable("MyTable");
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
dt.Columns.Add(new DataColumn("Col3", typeof(string)));
for (int i = 0; i < 3; i++)
{
DataRow row = dt.NewRow();
row["Col1"] = "col 1, row " + i;
row["Col2"] = "col 2, row " + i;
row["Col3"] = "col 3, row " + i;
dt.Rows.Add(row);
}
return View(dt); //passing the DataTable as my Model
}
View: (w/ Model strongly typed as System.Data.DataTable)
<table border="1">
<thead>
<tr>
<%foreach (System.Data.DataColumn col in Model.Columns) { %>
<th><%=col.Caption %></th>
<%} %>
</tr>
</thead>
<tbody>
<% foreach(System.Data.DataRow row in Model.Rows) { %>
<tr>
<% foreach (var cell in row.ItemArray) {%>
<td><%=cell.ToString() %></td>
<%} %>
</tr>
<%} %>
</tbody>
</table>
Now, I'm violating a whole lot of principles and "best-practices" of ASP.NET MVC here, so please understand this is just a simple demonstration. The code creating the DataTable should reside somewhere outside of the controller, and the code in the View might be better isolated to a partial, or html helper, to name a few ways you should do things.
You absolutely are supposed to pass objects to the View, if the view is supposed to present them. (Separation of concerns dictates the view shouldn't be responsible for creating them.) In this case I passed the DataTable as the actual view Model, but you could just as well have put it in ViewData collection. Alternatively you might make a specific IndexViewModel class that contains the DataTable and other objects, such as the welcome message.
I hope this helps!
I had the same problem, all I did was to restart the command line and then navigate to the document folder rather than the user folder using the command '' cd documents '' . That should be all thats needed. Also ensure that the link is correct.
This Link might be helpful for you.
Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().
It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.
If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.
You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)
The accepted answer lists only the filenames, but to get the top 5 files one can also use:
ls -lht | head -6
where:
-l
outputs in a list format
-h
makes output human readable (i.e. file sizes appear in kb, mb, etc.)
-t
sorts output by placing most recently modified file first
head -6
will show 5 files because ls
prints the block size in the first line of output.
I think this is a slightly more elegant and possibly more useful approach.
Example output:
total 26960312
-rw-r--r--@ 1 user staff 1.2K 11 Jan 11:22 phone2.7.py
-rw-r--r--@ 1 user staff 2.7M 10 Jan 15:26 03-cookies-1.pdf
-rw-r--r--@ 1 user staff 9.2M 9 Jan 16:21 Wk1_sem.pdf
-rw-r--r--@ 1 user staff 502K 8 Jan 10:20 lab-01.pdf
-rw-rw-rw-@ 1 user staff 2.0M 5 Jan 22:06 0410-1.wmv
value = value.setScale(2, RoundingMode.CEILING)
If you're using oh-my-zsh
Type
omz update
in the terminal
Note: upgrade_oh_my_zsh
is deprecated
Easy with kotlin
@Parcelize
class MyState(val superSavedState: Parcelable?, val loading: Boolean) : View.BaseSavedState(superSavedState), Parcelable
class MyView : View {
var loading: Boolean = false
override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
return MyState(superState, loading)
}
override fun onRestoreInstanceState(state: Parcelable?) {
val myState = state as? MyState
super.onRestoreInstanceState(myState?.superSaveState ?: state)
loading = myState?.loading ?: false
//redraw
}
}
I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.
So, I had to generate the SSL certificate again and it started working...
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt
For this html:
<div class="outer">
<div class="inner"></div>
</div>
This selector should work:
$('.outer > .inner')
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
You can use normal CSS selectors to select an element by name using jquery. Like this:
Button Code
<button type="button" name="mybutton">Click Me!</button>
Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});
Certainly the credit goes to @Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.
Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.
using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
foreach(var u in users)
{
DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
}
}
You need to make sure that the first numeral to the right of the decimal point is always displayed. In custom format strings, #
means display the number if it exists, and 0
means always display something, with 0 as the placeholder.
So in your case you will need something like:
=Format(Fields!CUL1.Value, "#,##0.##")
This saying: display 2 DP if they exist, for the non-zero part always display the lowest part, and use , as the grouping separator.
This is how it looks on your data (I've added a large value as well for reference):
If you're not interested in separating thousands, millions, etc, just use #0.##
as Paul-Jan suggested.
The standard docs for Custom Numeric Format Strings are your best reference here.
EDIT: Check if the api you’re interacting with is set to Content-Type: application/json
, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”
, instead of body: { ...normal payload }
). All I had to do was change the api to Content-Type: text/plain
, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.
ORIGINAL: If your Googles keep landing you here and your api throws errors unless your JSON double quotes are escaped ("{\"foo\": true}"
), all you need to do is stringify twice e.g. JSON.stringify(JSON.stringify(bar))
To make things easier asp Question 2 stated, you can make use of lambda method like this to save variable memory and to avoid navigating up and down in your view class
//method 1
findViewById(R.id.buttonSend).setOnClickListener(v -> {
// handle click
});
but if you wish to apply click event to your button at once in a method.
you can make use of Question 3 by @D. Tran answer. But do not forget to implement your view class with View.OnClickListener
.
In other to use Question #3 properly
Better to use:
DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key
The methods
in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file
system to verify that a particular Path exists
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}
In WPF it seems this code,
System.Windows.Forms.MessageBox.Show("Test");
is replaced with:
System.Windows.MessageBox.Show("Test");
The above answers address how to set the default minDate at init, but the question was actually how to dynamically alter the minDate, below I also clarify How to set the default minDate.
All that was wrong with the original question was that the minDate value being set should have been a string (don't forget the quotes):
$('#datePickerId').datepicker('option', 'minDate', '3');
minDate also accepts a date object and a common use is to have an end date you are trying to calculate so something like this could be useful:
$('#datePickerId').datepicker(
'option', 'minDate', new Date($(".datePop.start").val())
);
Just answering this for best practice; the minDate option expects one of:
@bogart setting the string to "0" is a solution as it satisfies option 2 above
$('#datePickerId').datepicker('minDate': '3');
<audio controls autoplay loop>
<source src="path/your_song.mp3" type="audio/ogg">
<embed src="path/your_song.mp3" autostart="true" loop="true" hidden="true">
</audio>
[ps. replace the "path/your_song.mp3" with the folder and the song title eg. "music/samplemusic.mp3" or "media/bgmusic.mp3" etc.
I hope it will help, it did the trick for me,
first, after connected my device to the computer I switch the paramater above to "camera device (PTP)";
then, I install PdaNet on my computer, finally all the usb driver were installed, and it works.
My smartphone is a samsung GS2, Android 4.4.2.
i've successfully removed dependencies of a package using this bash line:
for dep in $(pip show somepackage | grep Requires | sed 's/Requires: //g; s/,//g') ; do pip uninstall -y $dep ; done
this worked on pip 1.5.4
$('input:radio[name=q12_3]:checked').val();
Everything except for point 2 is correct. There are many different notations for signed ints, some implementations use the first, others use the last and yet others use something completely different. That all depends on the platform you're working with.
To insert a CR into XML, you need to use its character entity
.
This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.
Avoid multipart forms in Richfaces:
<h:form enctype="multipart/form-data">
<a4j:poll id="poll" interval="10000"/>
</h:form>
If you are using Richfaces, i have found that ajax requests inside of multipart forms return a new View ID on each request.
How to debug:
On each ajax request a View ID is returned, that is fine as long as the View ID is always the same. If you get a new View ID on each request, then there is a problem and must be fixed.
There's no need to use onAuthStateChanged() function in this scenario.
You can easily detect if the user is logged or not by executing:
var user = firebase.auth().currentUser;
For those who face the "returning null" issue, it's just because you are not waiting for the firebase call to complete.
Let's suppose you perform the login action on Page A and then you invoke Page B, on Page B you can call the following JS code to test the expected behavior:
var config = {
apiKey: "....",
authDomain: "...",
databaseURL: "...",
projectId: "..",
storageBucket: "..",
messagingSenderId: ".."
};
firebase.initializeApp(config);
$( document ).ready(function() {
console.log( "testing.." );
var user = firebase.auth().currentUser;
console.log(user);
});
If the user is logged then "var user" will contain the expected JSON payload, if not, then it will be just "null"
And that's all you need.
Regards
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerCalled) userInfo:nil repeats:NO];
-(void)timerCalled
{
NSLog(@"Timer Called");
// Your Code
}
Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here
You can use generic serial Comparator to sort collections by multiple fields.
import org.apache.commons.lang3.reflect.FieldUtils;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* @author MaheshRPM
*/
public class SerialComparator<T> implements Comparator<T> {
List<String> sortingFields;
public SerialComparator(List<String> sortingFields) {
this.sortingFields = sortingFields;
}
public SerialComparator(String... sortingFields) {
this.sortingFields = Arrays.asList(sortingFields);
}
@Override
public int compare(T o1, T o2) {
int result = 0;
try {
for (String sortingField : sortingFields) {
if (result == 0) {
Object value1 = FieldUtils.readField(o1, sortingField, true);
Object value2 = FieldUtils.readField(o2, sortingField, true);
if (value1 instanceof Comparable && value2 instanceof Comparable) {
Comparable comparable1 = (Comparable) value1;
Comparable comparable2 = (Comparable) value2;
result = comparable1.compareTo(comparable2);
} else {
throw new RuntimeException("Cannot compare non Comparable fields. " + value1.getClass()
.getName() + " must implement Comparable<" + value1.getClass().getName() + ">");
}
} else {
break;
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return result;
}
}
That's because you are using JSON Object. When you face such problems then change your JSON Object to JSON Array Object.
For Example,
{"India":"IN","America":"US","United Kingdon":"UK"} json object
[{"country":"India","countryId":"IN"},{"country":"America","countryId":"US"},{"country":"United Kingdon","countryId":"UK"}]
Line width in ggplot2
can be changed with argument lwd=
in geom_line()
.
geom_line(aes(x=..., y=..., color=...), lwd=1.5)
Keep in mind that readonly only applies to the value itself, so if you're using a reference type readonly only protects the reference from being change. The state of the instance is not protected by readonly.
See the wikipedia article on Unix signals for the list of other signals. SIGKILL just happened to get the number 9.
You can as well use the mnemonics, as the numbers:
kill -SIGKILL pid