document.getElementById("demo").innerHTML = voteable
finds the element with the id demo and then places the voteable
value into it; either too young or old enough.
So effectively <p id="demo"></p>
becomes for example <p id="demo">Old Enough</p>
I encountered the same problem and checked for null but it did not help. Because the script was loading before page load. So just by placing the script before the end body tag solved the problem.
If the case is accessing the IFrame via console, e. g. Chrome Dev Tools then you can just select the context of DOM requests via dropdown (see the picture).
.remove()
should remove all of them. I think the problem is that you're using an ID. There's only supposed to be one HTML element with a particular ID on the page, so jQuery is optimizing and not searching for them all. Use a class instead.
Quoting MDN
The
ChildNode.after()
method inserts a set of Node orDOMString
objects in the children list of thisChildNode
's parent, just after thisChildNode
. DOMString objects are inserted as equivalent Text nodes.
The browser support is Chrome(54+), Firefox(49+) and Opera(39+). It doesn't support IE and Edge.
var elm=document.getElementById('div1');
var elm1 = document.createElement('p');
var elm2 = elm1.cloneNode();
elm.append(elm1,elm2);
//added 2 paragraphs
elm1.after("This is sample text");
//added a text content
elm1.after(document.createElement("span"));
//added an element
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
In the snippet, I used another term append too
The property pDoc.parentElement
or pDoc.parentNode
will get you the parent element.
Actually, document.all
is only minimally comparable to document.getElementById
. You wouldn't use one in place of the other, they don't return the same things.
If you were trying to filter through browser capabilities you could use them as in Marcel Korpel's answer like this:
if(document.getElementById){ //DOM
element = document.getElementById(id);
} else if (document.all) { //IE
element = document.all[id];
} else if (document.layers){ //Netscape < 6
element = document.layers[id];
}
But, functionally, document.getElementsByTagName('*')
is more equivalent to document.all
.
For example, if you were actually going to use document.all
to examine all the elements on a page, like this:
var j = document.all.length;
for(var i = 0; i < j; i++){
alert("Page element["+i+"] has tagName:"+document.all(i).tagName);
}
you would use document.getElementsByTagName('*')
instead:
var k = document.getElementsByTagName("*");
var j = k.length;
for (var i = 0; i < j; i++){
alert("Page element["+i+"] has tagName:"+k[i].tagName);
}
You can use JQuery to ensure that all elements of the documents are ready before it starts the client side scripting
$(document).ready(
function()
{
document.getElementById(elmId).innerHTML = value;
}
);
You should not used document.getElementByID because its work only for client side controls which ids are fixed . You should use jquery instead like below example.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="foo">
<div class="bar">
Hello world!
</div>
</div>
use this :
$("[id^='foo']").find("[class^='bar']")
// do not forget to add script tags as above
if you want any remove edit any operation then just add "." behind and do the operations
use contentDocument
to achieve this
var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument)
? iframe.contentDocument
: iframe.contentWindow.document;
var ulObj = innerDoc.getElementById("ID_TO_SEARCH");
Script is called before element exists.
You should try one of the following:
Theres no shorthand way in vue 2.
Jeff's method seems already deprecated in vue 2.
Heres another way u can achieve your goal.
var app = new Vue({_x000D_
el:'#app',_x000D_
methods: { _x000D_
showMyDiv() {_x000D_
console.log(this.$refs.myDiv);_x000D_
}_x000D_
}_x000D_
_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
<div id="myDiv" ref="myDiv"></div>_x000D_
<button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
import React, { useState } from 'react';
function App() {
const [apes , setap] = useState('yo');
const handleClick = () =>{
setap(document.getElementById('name').value)
};
return (
<div>
<input id='name' />
<h2> {apes} </h2>
<button onClick={handleClick} />
</div>
);
}
export default App;
There could be many reason why document.getElementById
doesn't work
You have an invalid ID
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)
you used some id that you already used as <meta>
name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at
(resource: http://www.phpied.com/getelementbyid-description-in-ie/)
you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument
before looking for the element
(resource: Calling a specific id inside a frame)
you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling
I doubt you used same ID twice or more: in that case document.getElementById
should return at least the first element
Modern browsers have support for document.getElementsByClassName
. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.
You'll want to check into jQuery, which will allow the following:
$(".classname").hide(); // hides everything with class 'classname'
Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".classname").hide();
});
</script>
I'm not entirely sure I know what you're asking about, but you can use string functions to create the actual ID that you're looking for.
var base = "common";
var num = 3;
var o = document.getElementById(base + num); // will find id="common3"
If you don't know the actual ID, then you can't look up the object with getElementById, you'd have to find it some other way (by class name, by tag type, by attribute, by parent, by child, etc...).
Now that you've finally given us some of the HTML, you could use this plain JS to find all form elements that have an ID that starts with "poll-":
// get a list of all form objects that have the right type of ID
function findPollForms() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
results.push(list[i]);
}
}
return(results);
}
// return the ID of the first form object that has the right type of ID
function findFirstPollFormID() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
return(id);
}
}
return(null);
}
Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"
I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.
class ProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
id: this.props.id <--- ID set from <ProgressBar id="Progress1"/>
}
}
}
As mentioned in some of the answers above you absolutely can use document.querySelector
inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:
render () {
const id = this.state.id
return (<div id={"progress-bar-" + id}></div>)
}
Then you can elsewhere do a normal javascript querySelector call like this:
let element = document.querySelector('#progress-bar-Progress1')
Make sure your code is in DOM Ready as pointed by rocket-hazmat
$('#RootNode').click(function(){
//do something
});
document.getElementById("RootNode").onclick = function(){//do something}
$(document).on("click", "#RootNode", function(){
//do something
});
Wrap Code in Dom Ready
$(document).ready(function(){
$('#RootNode').click(function(){
//do something
});
});
You can also use this
document.querySelector('yourId').innerHTML = 'Content';
There are always weird issues with browser support of getElementById, try using the following instead:
// document.getElementsBySelector are part of the prototype.js library available at http://api.prototypejs.org/dom/Element/prototype/getElementsBySelector/
function disbtn(e) {
if ( someCondition == true ) {
document.getElementsBySelector("#btn1")[0].setAttribute("disabled", "disabled");
} else {
document.getElementsBySelector("#btn1")[0].removeAttribute("disabled");
}
}
Alternatively, embrace jQuery where you could simply do this:
function disbtn(e) {
if ( someCondition == true ) {
$("#btn1").attr("disabled", "disabled");
} else {
$("#btn1").removeAttr("disabled");
}
}
Because when the script executes the browser has not yet parsed the <body>
, so it does not know that there is an element with the specified id.
Try this instead:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = (function () {
var refButton = document.getElementById("btnButton");
refButton.onclick = function() {
alert('Dhoor shala!');
};
});
</script>
</head>
<body>
<form id="form1">
<div>
<input id="btnButton" type="button" value="Click me"/>
</div>
</form>
</body>
</html>
Note that you may as well use addEventListener
instead of window.onload = ...
to make that function only execute after the whole document has been parsed.
Use Math.ceil()
and cast the result to int:
Example:
(int) Math.ceil((double)divident / divisor);
You can use the standard Python idiom, vars()
:
for attr, value in vars(k).items():
print(attr, '=', value)
You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.
You can get the Java EE Edition of eclipse with has it pre-installed.
To create and run your first servlet:
doGet()
method.That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.
It's not a better idea to override the core.common file of codeigniter. Because that's the more tested and system files....
I make a solution for this problem. In your ckeditor_helper.php file line- 65
if($k !== end (array_keys($data['config']))) {
$return .= ",";
}
Change this to-->
$segment = array_keys($data['config']);
if($k !== end($segment)) {
$return .= ",";
}
I think this is the best solution and then your problem notice will dissappear.
If the string has always the same format, a simple substr()
should suffice.
var newString = originalStrint.substr(4)
I was having this problem because I was trying to connect to MySQL but I didn't have the required package. I figured it out because of @Amadan's comment to check the error log. In my case, I was having the error: Call to undefined function mysql_connect()
If your PHP file has any code to connect with a My-SQL db then you might need to install php5-mysql
first. I was getting this error because I hadn't installed it. All my file permissions were good. In Ubuntu, you can install it by the following command:
sudo apt-get install php5-mysql
public void onPressed(Button button, int drawable) {
if (!isPressed) {
button.setBackgroundResource(R.drawable.bg_circle);
isPressed = true;
} else {
button.setBackgroundResource(drawable);
isPressed = false;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.circle1:
onPressed(circle1, R.drawable.bg_circle_gradient);
break;
case R.id.circle2:
onPressed(circle2, R.drawable.bg_circle2_gradient);
break;
case R.id.circle3:
onPressed(circle3, R.drawable.bg_circle_gradient3);
break;
case R.id.circle4:
onPressed(circle4, R.drawable.bg_circle4_gradient);
break;
case R.id.circle5:
onPressed(circle5, R.drawable.bg_circle5_gradient);
break;
case R.id.circle6:
onPressed(circle6, R.drawable.bg_circle_gradient);
break;
case R.id.circle7:
onPressed(circle7, R.drawable.bg_circle4_gradient);
break;
}
please try this, in this code i m trying to change the background of button on button click this works fine.
Uninstall pg:
gem uninstall pg
Uninstall postgres:
brew uninstall postgres
Nuke the postgres folder which might be lingering with a bunch of stale stuff it in:
rm -rf /usr/local/var/postgres
Reboot (maybe unnecessary)
Reinstall pg:
brew install postgres
My comment in Chris Slade's answer starts pg the hard way, now I use brew services which has simplified my life in so many ways:
brew install services
And start pg with it:
brew services start postgresql
Reinstall the gem:
gem install pg
And bobsyouruncle.
You should not map score to player. You should map player (or his name) to score:
Map<Player, Integer> player2score = new HashMap<Player, Integer>();
Then add players to map: int score = .... Player player = new Player(); player.setName("John"); // etc. player2score.put(player, score);
In this case the task is trivial:
int score = player2score.get(player);
I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`
public void replaceFragment(BaseFragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
final FragmentManager fManager = getSupportFragmentManager();
BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
if (fragm == null) { //here fragment is not available in the stack
transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
transaction.addToBackStack(fragment.getFragmentTag());
} else {
//fragment was found in the stack , now we can reuse the fragment
// please do not add in back stack else it will add transaction in back stack
transaction.replace(R.id.container, fragm, fragm.getFragmentTag());
}
transaction.commit();
}
And in the onBackPressed()
@Override
public void onBackPressed() {
if(getSupportFragmentManager().getBackStackEntryCount()>1){
super.onBackPressed();
}else{
finish();
}
}
$(this)
is a jQuery object that is wrapping the DOM element this
and jQuery objects don't have id
properties. You probably want just this.id
to get the id
attribute of the clicked element.
Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.
>>> books = {}
>>> books['book'] = 3
>>> books['book'] -= 1
>>> books
{'book': 2}
In your case:
book_shop[ch1] -= 1
The first statement depends on the context in which it is declared.
If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.
If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"
EDIT:
I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.
END EDIT
Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore
var foo = function foo() { return 5; }
Is the same as
var foo = function fooYou() { return 5; }
@Filoche's Angular 2 updated solution. Using FormControl
(<Control>this.form.controls['dept']).updateValue(selected.id)
import { FormControl } from '@angular/forms';
(<FormControl>this.form.controls['dept']).setValue(selected.id));
Alternatively you can use @AngularUniversity's solution which uses patchValue
Unfortunately, I believe that is already the best way (although list()
is slightly better than listFiles()
, since it doesn't construct File
objects).
A single regular expression replace should do it:
var stringWithSmallIntegers = "4° 7' 34"W, 168° 1' 23"N";
var paddedString = stringWithSmallIntegers.replace(
/\d+/g,
function pad(digits) {
return digits.length === 1 ? '0' + digits : digits;
});
alert(paddedString);
shows the expected output.
An empty string has one single null byte. So test if (s[0] == (char)0)
Adding below lines in app level build.gradle in Android project solved issue.
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
works, however it results in a Python warning of
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value
instead
I would guess this is due to some chaining indexing.
Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'
You can run 20 processes and use the command:
wait
Your script will wait and continue when all your background jobs are finished.
I faced the same error, but only with files cloned from git that were assigned to a proprietary plugin. I realized that even after cloning the files from git, I needed to create a new project or import a project in eclipse and this resolved the error.
To answer your question, firstly I would strongly recommend looking at the Documentation.
Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.
We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.
I wrote an inherited class:
<?php_x000D_
class ExcelReader extends Spreadsheet_Excel_Reader { _x000D_
_x000D_
function GetInArray($sheet=0) {_x000D_
_x000D_
$result = array();_x000D_
_x000D_
for($row=1; $row<=$this->rowcount($sheet); $row++) {_x000D_
for($col=1;$col<=$this->colcount($sheet);$col++) {_x000D_
if(!$this->sheets[$sheet]['cellsInfo'][$row][$col]['dontprint']) {_x000D_
$val = $this->val($row,$col,$sheet);_x000D_
$result[$row][$col] = $val;_x000D_
}_x000D_
}_x000D_
}_x000D_
return $result;_x000D_
}_x000D_
_x000D_
}_x000D_
?>
_x000D_
So I can do this:
<?php_x000D_
_x000D_
$data = new ExcelReader("any_excel_file.xls");_x000D_
print_r($data->GetInArray());_x000D_
_x000D_
?>
_x000D_
What you want to do is a combination of part of 1 and all of 2.
You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.
From the javadoc:
Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.
The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.
Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.
Check this out,
body {
background-color: black;
background: url(img/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Use LoadXml Method of XmlDocument;
string xml = "<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer></body></head>";
xDoc.LoadXml(xml);
This solution will only add the border, the body of the LinearLayout will be transparent.
First, Create this border drawable in the drawable folder, border.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android= "http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:width="2dp" android:color="#ec0606"/>
<corners android:radius="10dp"/>
</shape>
Then, in your LinearLayout View, add the border.xml as the background like this
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/border">
What is the way to generate a patch only for the specific SHA1?
It's quite simple:
Option 1. git show commitID > myFile.patch
Option 2. git commitID~1..commitID > myFile.patch
Note: Replace commitID
with actual commit id (SHA1 commit code).
Tried everything possible.. here is final piece of working code. Hope it helps someone who is looking for it.
<?
$url='https://www.googleapis.com/plus/v1/people/116599978027440206136?fields=image%2Furl&key=MY_API_KEY&fields=image';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$d = json_decode($response);
$avatar_url = $d->{'image'}->{'url'};
echo $avatar_url;
?>
I finally got it, submited it 13 times rejected for whatever reasons, 14th "the judge" accepted my answer, here it is :
import java.io.BufferedInputStream;
import java.util.Scanner;
public class HashmatWarrior {
public static void main(String args[]) {
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
while (stdin.hasNext()) {
System.out.println(Math.abs(stdin.nextLong() - stdin.nextLong()));
}
}
}
Editing properties/my_app.properties file inside jar:
"zip -u /var/opt/my-jar-with-dependencies.jar properties/my_app.properties"
. Basically "zip -u <source> <dest>"
, where dest is relative to the jar extract folder.
Following are some things I found in my collection of obscure Ruby.
So, in Ruby, a simple no-bells implementation of the Unix command cat
would be:
#!/usr/bin/env ruby
puts ARGF.read
ARGF
is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.
ARGF.each_with_index do |line, idx|
print ARGF.filename, ":", idx, ";", line
end
# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
puts line if line =~ /login/
end
Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF
as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i
) to every file mentioned on the command-line:
#!/usr/bin/env ruby -i
Header = DATA.read
ARGF.each_line do |e|
puts Header if ARGF.pos - e.length == 0
puts e
end
__END__
#--
# Copyright (C) 2007 Fancypants, Inc.
#++
Credit to:
You can use SSMS's "Generate Scripts..." function to script out whatever you need to transfer. Right-click on the source database in SSMS, choose "Generate Scripts...", and follow the wizard along. Then run your resultant script that will now contain the stored procedure create statements.
SHORT ANSWER: We don't know how to do garbage collection efficiently (with minor time and space overhead) and correctly all the time (in all possible cases).
LONG ANSWER: Just like C, C++ is a systems language; this means it is used when you are writing system code, e.g., operating system. In other words, C++ is designed, just like C, with best possible performance as the main target. The language' standard will not add any feature that might hinder the performance objective.
This pauses the question: Why garbage collection hinders performance? The main reason is that, when it comes to implementation, we [computer scientists] do not know how to do garbage collection with minimal overhead, for all cases. Hence it's impossible to the C++ compiler and runtime system to perform garbage collection efficiently all the time. On the other hand, a C++ programmer, should know his design/implementation and he's the best person to decide how to best do the garbage collection.
Last, if control (hardware, details, etc.) and performance (time, space, power, etc.) are not the main constraints, then C++ is not the write tool. Other language might serve better and offer more [hidden] runtime management, with the necessary overhead.
Besides using Android Studio, you can also take a screenshot with adb which is faster.
adb shell screencap -p /sdcard/screen.png
adb pull /sdcard/screen.png
adb shell rm /sdcard/screen.png
Shorter one line alternative in Unix/OSX
adb shell screencap -p | perl -pe 's/\x0D\x0A/\x0A/g' > screen.png
Original blog post: Grab Android screenshot to computer via ADB
var rowHandle = gridView.FocusedRowHandle;
var obj = gridView.GetRowCellValue(rowHandle, "FieldName");
//For example
int val= Convert.ToInt32(gridView.GetRowCellValue(rowHandle, "FieldName"));
This can be caused if the client is in a different domain than the server.
I encountered this when testing one of my applications from my PC(client) to my (cloud) testing server and the simplest solution i could think of was setting up a vpn.
This is the correct way to change btn color.
.btn-primary:not(:disabled):not(.disabled).active,
.btn-primary:not(:disabled):not(.disabled):active,
.show>.btn-primary.dropdown-toggle{
color: #fff;
background-color: #F7B432;
border-color: #F7B432;
}
I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:
cscript myscript.vbs //nologo
any .Exec() calls in the myscript.vbs do not open an extra window, meaning that you can use the first variant of your original solution (using exec).
(Note that the two forward slashes in the above code are intentional, see cscript /?)
UILabel
has a property lineBreakMode
that you can set as per your requirement.
This script is a improvement of the script from Vector. I have made a little change to it. So this script works for every link with the class page-scroll in it.
At first without easing:
$("a.page-scroll").click(function() {
var targetDiv = $(this).attr('href');
$('html, body').animate({
scrollTop: $(targetDiv).offset().top
}, 1000);
});
For easing you will need Jquery UI:
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
Add this to the script:
'easeOutExpo'
Final
$("a.page-scroll").click(function() {
var targetDiv = $(this).attr('href');
$('html, body').animate({
scrollTop: $(targetDiv).offset().top
}, 1000, 'easeOutExpo');
});
All the easings you can find here: Cheat Sheet.
@bsimmons
git fsck --lost-found | grep commit
Then create a branch for each one:
$ git fsck --lost-found | grep commit
Checking object directories: 100% (256/256), done.
dangling commit 2806a32af04d1bbd7803fb899071fcf247a2b9b0
dangling commit 6d0e49efd0c1a4b5bea1235c6286f0b64c4c8de1
dangling commit 91ca9b2482a96b20dc31d2af4818d69606a229d4
$ git branch branch_2806a3 2806a3
$ git branch branch_6d0e49 6d0e49
$ git branch branch_91ca9b 91ca9b
Now many tools will show you a graphical visualization of those lost commits.
I guess you could open a popup window and call that a dialog box. I'm unsure of the details, but I'm pretty sure you can close a window programmatically that you opened from javascript. Would this suffice?
It may be faster if you create a materialized view (with schema binding). Non-materialized views execute just like the regular query.
Instead of $location.path(...)
to change or refresh the page, I used the service $window
. In Angular this service is used as interface to the window
object, and the window
object contains a property location
which enables you to handle operations related to the location or URL stuff.
For example, with window.location
you can assign a new page, like this:
$window.location.assign('/');
Or refresh it, like this:
$window.location.reload();
It worked for me. It's a little bit different from you expect but works for the given goal.
To convert JodaTime's org.joda.time.LocalDate
to java.sql.Timestamp
, just do
Timestamp timestamp = new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis());
To convert JodaTime's org.joda.time.LocalDateTime
to java.sql.Timestamp
, just do
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
To convert Java8's java.time.LocalDate
to java.sql.Timestamp
, just do
Timestamp timestamp = Timestamp.valueOf(localDate.atStartOfDay());
To convert Java8's java.time.LocalDateTime
to java.sql.Timestamp
, just do
Timestamp timestamp = Timestamp.valueOf(localDateTime);
You can get the full download here: http://download.microsoft.com/download/8/3/a/83aad8f9-38ba-4503-b3cd-ba28c360c27b/ENU/vcsetup.exe
=INDEX(GoogleFinance("CURRENCY:" & "EUR" & "USD", "price", A2), 2, 2)
where A2
is the cell with a date formatted as date.
Replace "EUR" and "USD" with your currency pair.
Couldn't find a solution I'm completely happy with (reasonable performance, but no unsafe code/pinvoke) so I came up with this, nothing really original, but works:
/// <summary>
///
/// </summary>
/// <param name="array1"></param>
/// <param name="array2"></param>
/// <param name="bytesToCompare"> 0 means compare entire arrays</param>
/// <returns></returns>
public static bool ArraysEqual(byte[] array1, byte[] array2, int bytesToCompare = 0)
{
if (array1.Length != array2.Length) return false;
var length = (bytesToCompare == 0) ? array1.Length : bytesToCompare;
var tailIdx = length - length % sizeof(Int64);
//check in 8 byte chunks
for (var i = 0; i < tailIdx; i += sizeof(Int64))
{
if (BitConverter.ToInt64(array1, i) != BitConverter.ToInt64(array2, i)) return false;
}
//check the remainder of the array, always shorter than 8 bytes
for (var i = tailIdx; i < length; i++)
{
if (array1[i] != array2[i]) return false;
}
return true;
}
Performance compared with some of the other solutions on this page:
Simple Loop: 19837 ticks, 1.00
*BitConverter: 4886 ticks, 4.06
UnsafeCompare: 1636 ticks, 12.12
EqualBytesLongUnrolled: 637 ticks, 31.09
P/Invoke memcmp: 369 ticks, 53.67
Tested in linqpad, 1000000 bytes identical arrays (worst case scenario), 500 iterations each.
If your Python SDK is properly configured and you are still facing the problem that builtins are not recognized, try this:
File -> Invalidate Caches/Restart
On CentOS7 I had to follow the third install method, get-docker.sh https://docs.docker.com/install/linux/docker-ce/centos/#install-using-the-convenience-script
This might be what you are after, although depending on how many style_id's there are, it would be tricky to implement (not sure if those style_id's are static or not). If this is the case, then it is not really possible what you are wanting as the WHERE clause works on a row to row basis.
WITH cte as (
SELECT
image_id,
max(decode(style_id,24,style_value)) AS style_colour,
max(decode(style_id,25,style_value)) AS style_size,
max(decode(style_id,27,style_value)) AS style_shape
FROM
list
GROUP BY
image_id
)
SELECT
image_id
FROM
cte
WHERE
style_colour = 'red'
and style_size = 'big'
and style_shape = 'round'
In the ideal world you would set the text style attribute in you layout XML definition like that:
<TextView
android:id="@+id/TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"/>
There is a simple way to achieve the same result dynamically in your code by using setTypeface
method. You need to pass and object of Typeface class, which will describe the font style for that TextView. So to achieve the same result as with the XML definition above you can do the following:
TextView Tv = (TextView) findViewById(R.id.TextView);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
Tv.setTypeface(boldTypeface);
The first line will create the object form predefined style (in this case Typeface.BOLD, but there are many more predefined). Once we have an instance of typeface we can set it on the TextView. And that's it our content will be displayed on the style we defined.
I hope it helps you a lot.For better info you can visit
http://developer.android.com/reference/android/graphics/Typeface.html
You should get rid of the 2-power part of N right from the start.
2nd Edit The magical expression for m below should be
m = N - (N & (N-1));
and not as written
End of 2nd edit
m = N & (N-1); // the lawest bit of N
N /= m;
byte = N & 0x0F;
if ((m % 2) || (byte !=1 && byte !=9))
return false;
1st Edit:
Minor improvement:
m = N & (N-1); // the lawest bit of N
N /= m;
if ((m % 2) || (N & 0x07 != 1))
return false;
End of 1st edit
Now continue as usual. This way, by the time you get to the floating point part, you already got rid of all the numbers whose 2-power part is odd (about half), and then you only consider 1/8 of whats left. I.e. you run the floating point part on 6% of the numbers.
You can write "localhost" or "127.0.0.1" but URL must be the same
Example : Google Domains Add-> localhost URL => localhost/login.php
Example : Google Domains Add-> 127.0.0.1 URL => 127.0.0.1/login.php
You should use form tag enclosing your inputs. And input type submit.
This works.
<form id="testform">
<input type="text" id="example" name="example" required>
<button type="submit" onclick="submitform()" id="save">Save</button>
</form>
Since HTML5 Validation works only with submit button you have to keep it there. You can avoid the form submission though when valid by preventing the default action by writing event handler for form.
document.getElementById('testform').onsubmit= function(e){
e.preventDefault();
}
This will give your validation when invalid and will not submit form when valid.
When using aggregate functions to filter, you must use a HAVING statement.
SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500
What would be useful here would be a LIKE ANY
predicate as is available in PostgreSQL
SELECT *
FROM tbl
WHERE my_col LIKE ANY (ARRAY['%val1%', '%val2%', '%val3%', ...])
Unfortunately, that syntax is not available in Oracle. You can expand the quantified comparison predicate using OR
, however:
SELECT *
FROM tbl
WHERE my_col LIKE '%val1%' OR my_col LIKE '%val2%' OR my_col LIKE '%val3%', ...
Or alternatively, create a semi join using an EXISTS
predicate and an auxiliary array data structure (see this question for details):
SELECT *
FROM tbl t
WHERE EXISTS (
SELECT 1
-- Alternatively, store those values in a temp table:
FROM TABLE (sys.ora_mining_varchar2_nt('%val1%', '%val2%', '%val3%'/*, ...*/))
WHERE t.my_col LIKE column_value
)
For true full-text search, you might want to look at Oracle Text: http://www.oracle.com/technetwork/database/enterprise-edition/index-098492.html
If you're open to another Perl solution:
perl -ple 's/^(\S+)\s+(.*)/$2 $1/' file
The main differenece is that bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions.
Note that navigational access is not always good, especially for "one-to-very-many" and "many-to-very-many" relationships. Imagine a Group
that contains thousands of User
s:
How would you access them? With so many User
s, you usually need to apply some filtering and/or pagination, so that you need to execute a query anyway (unless you use collection filtering, which looks like a hack for me). Some developers may tend to apply filtering in memory in such cases, which is obviously not good for performance. Note that having such a relationship can encourage this kind of developers to use it without considering performance implications.
How would you add new User
s to the Group
? Fortunately, Hibernate looks at the owning side of relationship when persisting it, so you can only set User.group
. However, if you want to keep objects in memory consistent, you also need to add User
to Group.users
. But it would make Hibernate to fetch all elements of Group.users
from the database!
So, I can't agree with the recommendation from the Best Practices. You need to design bidirectional relationships carefully, considering use cases (do you need navigational access in both directions?) and possible performance implications.
See also:
aws ecr get-login --region us-west-1 --no-include-email
This command gives me correct command to login. If you dont use "--no-include-email",it will throw another error. Output of the above command looks like this docker login -u AWS -p **********************very big******. Copy that and execute it. Now it will show "Login Succeeded". Now you can push your image to ECR.
Make sure that your AMI rule has the permission for the user you tried to login.
For
throw new Exception('test exception');
I got 500 (but didn't see anything in the browser), until I put
php_flag display_errors on
in my .htaccess (just for a subfolder). There are also more detailed settings, see Enabling error display in php via htaccess only
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:
var keys = Object.keys(myObject);
The above has a full polyfill but a simplified version is:
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
Alternatively replace var getKeys
with Object.prototype.keys
to allow you to call .keys()
on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.
Since :last-child
is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child
is supported, as it's defined in the CSS2.1 specification.
One possible solution is to simply give the last child a class name and style that class.
Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child
pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.
One additional benefit to doing it in javascript is you can add / remove the hover effect at different points in time - e.g. hover over table rows changes color, click disables the hover effect and starts edit in place mode.
I've done something like this using Spring AOP so I could grab the sql, parameters, errors, and execution time for any query run in the application whether it was HQL, Criteria, or native SQL.
This is obviously fragile, insecure, subject to break with changes in Hibernate, etc, but it illustrates that it's possible to get the SQL:
CriteriaImpl c = (CriteriaImpl)query;
SessionImpl s = (SessionImpl)c.getSession();
SessionFactoryImplementor factory = (SessionFactoryImplementor)s.getSessionFactory();
String[] implementors = factory.getImplementors( c.getEntityOrClassName() );
CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable)factory.getEntityPersister(implementors[0]),
factory, c, implementors[0], s.getEnabledFilters());
Field f = OuterJoinLoader.class.getDeclaredField("sql");
f.setAccessible(true);
String sql = (String)f.get(loader);
Wrap the entire thing in a try/catch and use at your own risk.
You can't. A redirect requires a webserver to accept the first request and send back the redirect. The "hosts" file just lets you set your own DNS records.
all of above answers would help you but you have to add three ports in the firewall of PC on which SQL Server is installed.
Add new TCP Local port in Windows firewall at port no. 1434
Add new program for SQL Server and select sql server.exe Path: C:\ProgramFiles\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Binn\sqlservr.exe
Add new program for SQL Browser and select sqlbrowser.exe Path: C:\ProgramFiles\Microsoft SQL Server\90\Shared\sqlbrowser.exe
You can use wget
command to download the page and read it into a variable as:
content=$(wget google.com -q -O -)
echo $content
We use the -O
option of wget
which allows us to specify the name of the file into which wget
dumps the page contents. We specify -
to get the dump onto standard output and collect that into the variable content
. You can add the -q
quiet option to turn off's wget output.
You can use the curl command for this aswell as:
content=$(curl -L google.com)
echo $content
We need to use the -L
option as the page we are requesting might have moved. In which case we need to get the page from the new location. The -L
or --location
option helps us with this.
In a .java file,there can be only one public top-level class whose name is the same as the file, but there might be several public inner classes which can be exported to everyone and access the outer class's fields/methods,for example:AlertDialog.Builder(modified by 'public static') in AlertDialog(modified by 'public')
You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]
A one-liner command in Windows PowerShell to delete or rename certain characters will be as below. (here the whitespace is being replaced with underscore)
Dir | Rename-Item –NewName { $_.name –replace " ","_" }
When you call figure
, simply number the plot.
x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)
z = np.sin(x)
plt.figure(1)
plt.plot(x, z)
w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)
Edit: Note that you can number the plots however you want (here, starting from 0
) but if you don't provide figure with a number at all when you create a new one, the automatic numbering will start at 1
("Matlab Style" according to the docs).
For IntelliJ Mac / IOS,
Click on IntelliJ IDEA
text besides on top left corner then Preferences->Editor->Color Scheme-> Select the required one
You can modify the whole InfoWindow using jquery alone...
var popup = new google.maps.InfoWindow({
content:'<p id="hook">Hello World!</p>'
});
Here the <p> element will act as a hook into the actual InfoWindow. Once the domready fires, the element will become active and accessible using javascript/jquery, like $('#hook').parent().parent().parent().parent()
.
The below code just sets a 2 pixel border around the InfoWindow.
google.maps.event.addListener(popup, 'domready', function() {
var l = $('#hook').parent().parent().parent().siblings();
for (var i = 0; i < l.length; i++) {
if($(l[i]).css('z-index') == 'auto') {
$(l[i]).css('border-radius', '16px 16px 16px 16px');
$(l[i]).css('border', '2px solid red');
}
}
});
You can do anything like setting a new CSS class or just adding a new element.
Play around with the elements to get what you need...
Swift
If you are not using object then you can user this code for contains.
let elements = [ 10, 20, 30, 40, 50]
if elements.contains(50) {
print("true")
}
If you are using NSObject Class in swift. This variables is according to my requirement. you can modify for your requirement.
var cliectScreenList = [ATModelLeadInfo]()
var cliectScreenSelectedObject: ATModelLeadInfo!
This is for a same data type.
{ $0.user_id == cliectScreenSelectedObject.user_id }
If you want to AnyObject type.
{ "\($0.user_id)" == "\(cliectScreenSelectedObject.user_id)" }
Full condition
if cliectScreenSelected.contains( { $0.user_id == cliectScreenSelectedObject.user_id } ) == false {
cliectScreenSelected.append(cliectScreenSelectedObject)
print("Object Added")
} else {
print("Object already exists")
}
I had to add a Refresh() statement after the Image = null to make things work.
MSDocs state this for your scenario:
In order to execute the first time, PackageManagement requires an internet connection to download the Nuget package provider. However, if your computer does not have an internet connection and you need to use the Nuget or PowerShellGet provider, you can download them on another computer and copy them to your target computer. Use the following steps to do this:
Run
Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force
to install the provider from a computer with an internet connection.After the install, you can find the provider installed in
$env:ProgramFiles\PackageManagement\ReferenceAssemblies\\\<ProviderName\>\\\<ProviderVersion\>
or$env:LOCALAPPDATA\PackageManagement\ProviderAssemblies\\\<ProviderName\>\\\<ProviderVersion\>
.Place the folder, which in this case is the Nuget folder, in the corresponding location on your target computer. If your target computer is a Nano server, you need to run Install-PackageProvider from Nano Server to download the correct Nuget binaries.
Restart PowerShell to auto-load the package provider. Alternatively, run
Get-PackageProvider -ListAvailable
to list all the package providers available on the computer. Then useImport-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201
to import the provider to the current Windows PowerShell session.
To explain in common usecase/purpose or layman way:
TrustStore : As the name indicates, its normally used to store the certificates of trusted entities. A process can maintain a store of certificates of all its trusted parties which it trusts.
keyStore : Used to store the server keys (both public and private) along with signed cert.
During the SSL handshake,
A client tries to access https://
And thus, Server responds by providing a SSL certificate (which is stored in its keyStore)
Now, the client receives the SSL certificate and verifies it via trustStore (i.e the client's trustStore already has pre-defined set of certificates which it trusts.). Its like : Can I trust this server ? Is this the same server whom I am trying to talk to ? No middle man attacks ?
Once, the client verifies that it is talking to server which it trusts, then SSL communication can happen over a shared secret key.
Note : I am not talking here anything about client authentication on server side. If a server wants to do a client authentication too, then the server also maintains a trustStore to verify client. Then it becomes mutual TLS
You should include json
in your file
For Example,
require 'json'
your_hash = {one: "1", two: "2"}
your_hash.to_json
For more knowledge about json
you can visit below link.
Json Learning
Your JavaScript file is missing so this error occurred. Just add the JavaScript file inside the <head>
tag. See the example:
<script src="js/sample.js" type="text/javascript"></script>
<link href="css/sample.css" rel="stylesheet" type="text/css" />
or add the following code in tag :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
The Groovy way to do this is
def list = []
list << new MyType(...)
which creates a list and uses the overloaded leftShift
operator to append an item
See the Groovy docs on Lists for lots of examples.
I was having the same problem today.. and has been searching for answers.. I am on Ubuntu... however, I could not find the correct one that works on this thread.. after much research the following worked for me finally!! :)
First, after running
mongod dbpath
if appeared that mongodb was looking for the data/db directory.. which was missing in my installed mongodb app.. so I ran the following commands:
$ sudo mkdir -p /data/db
then run,
$ sudo chown -R $USER /data/db
chown - changes ownership of files/dirs. Ie. owner of the file/dir changes to the specified one, but it doesn't modify permissions. As detailed here: https://unix.stackexchange.com/questions/402062/how-are-chown-and-chmod-command-different-in-the-given-operation
Finally, run
`$ sudo systemctl enable mongod.service
It will give a message: Created symlink /etc/systemd/system/multi-user.target.wants/mongod.service ? /lib/systemd/system/mongod.service and started the service.
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.
Set the following two environment variables:
NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0
where gpu_id
is the ID of your selected GPU, as seen in the host system's nvidia-smi
(a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).
You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id
parameter in nvidia-smi
run in a terminal in the guest system).
This method based on NVIDIA_VISIBLE_DEVICES
exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES
to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).
Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0
or env
in Kubernetes or Openshift.
If you want GPU load-balancing, make gpu_id
random at each guest system start.
If setting this with python, make sure you are using strings for all environment variables, including numerical ones.
You can verify that a different card is selected for each value of gpu_id
by inspecting nvidia-smi
's Bus-Id parameter (in a terminal run in the guest system).
The accepted solution based on CUDA_VISIBLE_DEVICES
alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).
This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu
), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).
This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.
The shortest command to fix it on Debian and Ubuntu (dependencies will be installed automatically):
sudo apt install php-zip
If you really want one line per user, you can group by grantee (require PG9+ for string_agg)
SELECT grantee, string_agg(privilege_type, ', ') AS privileges
FROM information_schema.role_table_grants
WHERE table_name='mytable'
GROUP BY grantee;
This should output something like :
grantee | privileges
---------+----------------
user1 | INSERT, SELECT
user2 | UPDATE
(2 rows)
There's a free extension you can download here that lets you duplicate lines without replacing the clipboard contents.
By default its bound to Alt + D, but you can change it to anything you want by going to Tools->Options->Environment->Keyboard. Type "Duplicate" in the search box and look for "Edit.DuplicateSelection" and edit the shortcut to whatever you want. I prefer Ctrl + D to be consistent with other editors.
Let's make some kind of summary:
Error message "The provider is not compatible with the version of Oracle client" can be caused by several reasons.
You have no Oracle Client installed. In this case the error message is indeed misleading.
Oracle Data Provider for .NET (ODP.NET, i.e. file Oracle.DataAccess.dll
) is not included in Oracle Instant Client, it has to be installed separately (download from 32-bit Oracle Data Access Components (ODAC) or 64-bit Oracle Data Access Components (ODAC) Downloads) or you have to select according option in Oracle Universal Installer (OUI).
Note, when installing the Oracle Data Provider >= 12.1, then the provider is not automatically registered into GAC. You have to register it manually if needed, see Oracle Doc 2272241.1.
The version of ODP.NET does not match installed version of Oracle Client. You have to check even the minor version number! For example, Oracle.DataAccess.dll
Version 4.112.3.0 is not compatible with Oracle Client 11.2.0.4. Check versions of ODP.NET and Oracle Client carefully. You can use sigcheck on oraociei*.dll
and/or OraOps*w.dll
to get version of Oracle Client.
Be aware of different numbering scheme. File version 4.112.3.0 means: .NET Framework Version 4, Oracle Release 11.2.0.3.x.
There are ODP.NET version "1.x", "2.x" and "4.x". These numbers are related to Microsoft .NET Framework versions 1.0.3705/1.1.4322, 2.0.50727 and 4.0.30319. Version "1.x" was available until Oracle Client 11.1. Version "4.x" was introduced with Oracle Client 11.2
The architecture (32bit or 64bit) of ODP.NET does not match your application architecture. A 32bit application works only with 32bit Oracle Client/ODP.NET respectively a 64bit application requires 64bit Oracle Client/ODP.NET. (Unless you use ODP.NET Managed Driver)
The .NET Framework version do not match. For example, if you compile your application with Target .NET Framework 2.0 then you cannot use ODP.NET version 4.x. The .NET Framework target version must be equal or higher than version of ODP.NET.
The version of Oracle.DataAccess.dll
on your development machine (i.e. the version which is loaded while compiling) is higher than the version on the target machine.
Be aware that Oracle.DataAccess.dll
might be loaded from GAC which by default takes precedence over any locally provided file.
Solutions
Consider to use the ODP.NET Managed Driver, it can be downloaded from Oracle page: 64-bit Oracle Data Access Components (ODAC) Downloads.
There you only have to copy Oracle.ManagedDataAccess.dll
file to your application directory, nothing else is required. It works for both 32bit and 64bit.
In your *.csproj
, resp. *.vbproj
edit your reference to ODP.NET like this:
<Reference Include="Oracle.DataAccess">
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
</Reference>
Attributes like Version=...
or processorArchitecture=...
are not required. Your application will load the correct -> not 100% verifiedOracle.DataAccess.dll
depending on selected architecture and target .NET framework (provided that it is installed properly)
In case you do not know the version of Oracle Client on target machine (e.g. it might be the machine of your customer): Go to the download page mentioned above and download the least XCopy version of Oracle Data Access Components. Extract the zip and copy just the Oracle.DataAccess.dll
file to your local machine. In your VS project make a reference to this (most likely outdated) DLL. The version of this DLL is the least version of ODP.NET your application will work with. When you run your application then the Publisher Policy in GAC will redirect to actually installed version.
I don't think it is a smart approach to take single DLL's and copy them to certain folders. It may work on a "naked" machine but if your target machine has installed any Oracle products there is a high risk for version mismatch. Uninstall any Oracle products from your machine and make a fresh installation. Have a look at How to uninstall / completely remove Oracle 11g (client)? it order to get a really clean machine.
In case you have to work with 32bit and 64bit applications at the same time, follow this instruction to install both versions on one machine:
Assumptions: Oracle Home is called OraClient11g_home1
, Client Version is 11gR2.
Optionally remove any installed Oracle client
Download and install Oracle x86 Client, for example into C:\Oracle\11.2\Client_x86
Download and install Oracle x64 Client into different folder, for example to C:\Oracle\11.2\Client_x64
Open command line tool, go to folder %WINDIR%\System32, typically C:\Windows\System32
and create a symbolic link ora112
to folder C:\Oracle\11.2\Client_x64
(see below)
Change to folder %WINDIR%\SysWOW64, typically C:\Windows\SysWOW64
and create a symbolic link ora112
to folder C:\Oracle\11.2\Client_x86
, (see below)
Modify the PATH
environment variable, replace all entries like C:\Oracle\11.2\Client_x86
and C:\Oracle\11.2\Client_x64
by C:\Windows\System32\ora112
, respective their \bin
subfolder. Note: C:\Windows\SysWOW64\ora112
must not be in PATH environment.
If needed set yor ORACLE_HOME
environment variable to C:\Windows\System32\ora112
Open your Registry Editor. Set Registry value HKLM\Software\ORACLE\KEY_OraClient11g_home1\ORACLE_HOME
to C:\Windows\System32\ora112
Set Registry value HKLM\Software\Wow6432Node\ORACLE\KEY_OraClient11g_home1\ORACLE_HOME
to C:\Windows\System32\ora112
(not C:\Windows\SysWOW64\ora112
)
You are done! Now you can use x86 and x64 Oracle client seamless together, i.e. an x86 application will load the x86 libraries, an x64 application loads the x64 libraries without any further modification on your system.
Commands to create symbolic links:
cd C:\Windows\System32
mklink /d ora112 C:\Oracle\11.2\Client_x64
cd C:\Windows\SysWOW64
mklink /d ora112 C:\Oracle\11.2\Client_x86
Some notes:
Both symbolic links must have the same name, e.g. ora112
.
In case you want to install ODP.NET manually afterwards, take care to select appropriate folders for installation.
Despite of their names folder C:\Windows\System32
contains the x64 libraries, whereas C:\Windows\SysWOW64
contains the x86 (32-bit) libraries. Don't be confused.
Maybe it is a wise option to set your TNS_ADMIN
environment variable (resp. TNS_ADMIN
entries in Registry) to a common location, for example TNS_ADMIN=C:\Oracle\Common\network
.
Perhaps:
> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)
Since Rails 4.2, without additional gems, you can load config/hi.yml simply by using Rails.application.config_for :hi
.
For example:
touch config/passwords.yml
#config/passwords.yml
development:
username: 'a'
password: 'b'
production:
username: 'aa'
password: 'bb'
touch config/initializers/constants.rb
#config/initializers/constants.rb
AUTHENTICATION = Rails.application.config_for :passwords
and now you can use AUTHENTICATION
constant everywhere in your application:
#rails c production
:001> AUTHENTICATION['username'] => 'aa'
then add passwords.yml to .gitignore: echo /config/passwords.yml >> .gitignore
, create an example file for your comfort cp /config/passwords.yml /config/passwords.example.yml
and then just edit your example file in your production console with actual production values.
This block of code makes a path of your app directory in string type
string path="";
path=System.AppContext.BaseDirectory;
good luck
integer excract from any string
$in = 'tel.123-12-33';
preg_match_all('!\d+!', $in, $matches);
$out = (int)implode('', $matches[0]);
//$out ='1231233';
ALTER PROCEDURE LN
(
@Firstname nvarchar(200)
)
AS
BEGIN
UPDATE tbl_Students1
SET Firstname=@Firstname
WHERE Studentid=3
END
exec LN 'Thanvi'
WARNING: Necromancing
Still Darin Dimitrov's answer + System.Security.SecurityElement.Escape(string s) isn't complete.
In XML 1.1, the simplest and safest way is to just encode EVERYTHING.
Like 	
for \t.
It isn't supported at all in XML 1.0.
For XML 1.0, one possible workaround is to base-64 encode the text containing the character(s).
//string EncodedXml = SpecialXmlEscape("?????? ???");
//Console.WriteLine(EncodedXml);
//string DecodedXml = XmlUnescape(EncodedXml);
//Console.WriteLine(DecodedXml);
public static string SpecialXmlEscape(string input)
{
//string content = System.Xml.XmlConvert.EncodeName("\t");
//string content = System.Security.SecurityElement.Escape("\t");
//string strDelimiter = System.Web.HttpUtility.HtmlEncode("\t"); // XmlEscape("\t"); //XmlDecode("	");
//strDelimiter = XmlUnescape(";");
//Console.WriteLine(strDelimiter);
//Console.WriteLine(string.Format("&#{0};", (int)';'));
//Console.WriteLine(System.Text.Encoding.ASCII.HeaderName);
//Console.WriteLine(System.Text.Encoding.UTF8.HeaderName);
string strXmlText = "";
if (string.IsNullOrEmpty(input))
return input;
System.Text.StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.Length; ++i)
{
sb.AppendFormat("&#{0};", (int)input[i]);
}
strXmlText = sb.ToString();
sb.Clear();
sb = null;
return strXmlText;
} // End Function SpecialXmlEscape
XML 1.0:
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
A more modern version of kaiido's answer using fetch would be:
function toObjectUrl(url) {
return fetch(url)
.then((response)=> {
return response.blob();
})
.then(blob=> {
return URL.createObjectURL(blob);
});
}
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Edit: As pointed out in the comments this will return an object url which points to a file in your local system instead of an actual DataURL so depending on your use case this might not be what you need.
You can look at the following answer to use fetch and an actual dataURL: https://stackoverflow.com/a/50463054/599602
In jquery ui modal dialogs you need to use this construct:
$( "#my_dialog" ).dialog( "option", "title", "my new title" );
I tried above all and end-up with few changes which I would like to share. Here's the code which works for me (find the attached screenshot):
<div class="input-group">
<input type="text" class="form-control" placeholder="Search text">
<span class="input-group-btn" style="width:0;">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div>
If you want to see it working, just use below code in you editor:
<html>
<head>
<link type='text/css' rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' />
</head>
<body>
<div class="container body-content">
<div class="form-horizontal">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search text">
<span class="input-group-btn" style="width:0;">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div>
</div>
</div>
</body>
</html>
Hope this helps.
Try this:
public class Team
{
public int TeamId { get; set;}
public string Name { get; set; }
public virtual ICollection<Match> HomeMatches { get; set; }
public virtual ICollection<Match> AwayMatches { get; set; }
}
public class Match
{
public int MatchId { get; set; }
public int HomeTeamId { get; set; }
public int GuestTeamId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
public class Context : DbContext
{
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Match>()
.HasRequired(m => m.HomeTeam)
.WithMany(t => t.HomeMatches)
.HasForeignKey(m => m.HomeTeamId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Match>()
.HasRequired(m => m.GuestTeam)
.WithMany(t => t.AwayMatches)
.HasForeignKey(m => m.GuestTeamId)
.WillCascadeOnDelete(false);
}
}
Primary keys are mapped by default convention. Team must have two collection of matches. You can't have single collection referenced by two FKs. Match is mapped without cascading delete because it doesn't work in these self referencing many-to-many.
put a semicolon between the two functions as statement terminator.
Regex is compiled so for speed create it once and reuse it.
The new takes longer than the IsMatch.
This only checks for all digits.
It does not check for range.
If you need to test range then TryParse is the way to go.
private static Regex regexInt = new Regex("^\\d+$");
static bool CheckReg(string value)
{
return regexInt.IsMatch(value);
}
If you want to do this through XCode's Interface Builder, you can use the menu options under Editor->Arrangement. There you'll find "Send to Front", "Send to Back", etc.
SELECT COALESCE(prereq, '') FROM test
Coalesce will return the first non-null argument passed to it from left to right. If all arguemnts are null, it'll return null, but we're forcing an empty string there, so no null values will be returned.
Also note that the COALESCE operator is supported in standard SQL. This is not the case of IFNULL. So it is a good practice to get use the former. Additionally, bear in mind that COALESCE supports more than 2 parameters and it will iterate over them until a non-null coincidence is found.
From ggplot 2.2.0
labels can easily be stacked by using position = position_stack(vjust = 0.5)
in geom_text
.
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))
Also note that "position_stack()
and position_fill()
now stack values in the reverse order of the grouping, which makes the default stack order match the legend."
Answer valid for older versions of ggplot
:
Here is one approach, which calculates the midpoints of the bars.
library(ggplot2)
library(plyr)
# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year),
transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)
# library(dplyr) ## If using dplyr...
# Data <- group_by(Data,Year) %>%
# mutate(pos = cumsum(Frequency) - (0.5 * Frequency))
# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
geom_bar(aes(fill = Category), stat="identity") +
geom_text(aes(label = Frequency, y = pos), size = 3)
Assuming that windowing works on SQL Server 2008 like it does elsewhere (that I've tried), give this a go:
select testtable.*, sum(somevalue) over(order by somedate)
from testtable
order by somedate;
MSDN says it's available in SQL Server 2008 (and maybe 2005 as well?) but I don't have an instance to hand to try it.
EDIT: well, apparently SQL Server doesn't allow a window specification ("OVER(...)") without specifying "PARTITION BY" (dividing the result up into groups but not aggregating in quite the way GROUP BY does). Annoying-- the MSDN syntax reference suggests that its optional, but I only have SqlServer 2000 instances around at the moment.
The query I gave works in both Oracle 10.2.0.3.0 and PostgreSQL 8.4-beta. So tell MS to catch up ;)
If you are using cordova, try cordova clean command
EDIT
As of today with flexbox, you could
body {
display:flex; flex-direction:column; justify-content:center;
min-height:100vh;
}
PREVIOUS ANSWER
html, body {height:100%;}
html {display:table; width:100%;}
body {display:table-cell; text-align:center; vertical-align:middle;}
select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m');
or
select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m');
hard to tell from your example
opt
is new for ruby 1.9. The various options are documented in IO.new
: www.ruby-doc.org/core/IO.html
This is Perfect. try this one :)
<form name="test" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
/* Html Input Fields */
</form>
Assume the following scenario:
composer.json
"parsecsv/php-parsecsv": "0.*"
composer.lock file
"name": "parsecsv/php-parsecsv",
"version": "0.1.4",
Latest release is
1.1.0
. The latest0.*
release is0.3.2
install: composer install parsecsv/php-parsecsv
This will install version 0.1.4
as specified in the lock file
update: composer update parsecsv/php-parsecsv
This will update the package to 0.3.2
. The highest version with respect to your composer.json. The entry in composer.lock
will be updated.
require: composer require parsecsv/php-parsecsv
This will update or install the newest version 1.1.0
. Your composer.lock
file and composer.json
file will be updated as well.
Give this a try...
server {
listen 80;
server_name dev.int.com;
access_log off;
location / {
proxy_pass http://IP:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:8080/jira /;
proxy_connect_timeout 300;
}
location ~ ^/stash {
proxy_pass http://IP:7990;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:7990/ /stash;
proxy_connect_timeout 300;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}
}
For using the string header first we must have include string header file as #include <string>
and then we can include string header in the following ways in C++:
1)
string header = "--- Demonstrates Unformatted Input ---";
2)
string header("**** Counts words****\n"), prompt("Enter a text and terminate"
" with a period and return:"), line( 60, '-'), text;
If you're using Mongo on Meteor, you can use _ensureIndex
:
CollectionName._ensureIndex({field:1 }, {unique: true});
Issue is with remote server, can you login to the remote server and check if "scp" works
probable causes: - scp is not in path - openssh client not installed correctly
for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/
yet another solution which uses the fact that np.nan != np.nan
:
In [149]: df.query("EPS == EPS")
Out[149]:
STK_ID EPS cash
STK_ID RPT_Date
600016 20111231 600016 4.3 NaN
601939 20111231 601939 2.5 NaN
I know this was answered long ago, but if you don't mind creating the button dynamically, this works using only the jQuery framework:
$(document).ready(function() {_x000D_
$button = $('<input id="1" type="button" value="ahaha" />');_x000D_
$('body').append($button);_x000D_
$button.click(function() {_x000D_
console.log("Id clicked: " + this.id ); // or $(this) or $button_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>And here is my HTML page:</p>_x000D_
_x000D_
<div class="Title">Welcome!</div>
_x000D_
In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:
def max(*values)
values.max
end
Output:
max(7, 1234, 9, -78, 156)
=> 1234
This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil
, since calling Enumerable#max on an empty array object returns nil
.
If you want to define this method on the Math module, this should do the trick:
module Math
def self.max(*values)
values.max
end
end
Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:
). See Dave Morse's answer for a simpler and faster method.
Another tool you can use is registry-cli. For example, this command:
registry.py -l "login:password" -r https://your-registry.example.com --delete
will delete all but the last 10 images.
Try the solution using the FileReader
class:
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file); // prints the base64 string
Notice that .files[0]
is a File
type, which is a sublcass of Blob
. Thus it can be used with FileReader
.
See the complete working example.
head -1 file.tsv |head -1 train.tsv |tr '\t' '\n' |wc -l
take the first line, change tabs (or you can use ',' instead of '\t' for commas), count the number of lines.
Thanks for your replies. Here's what I did:
git gc
git gc --aggressive
git prune
That seemed to have done the trick. I started with around 10.5MB and now it's little more than 980KBs.
I changed the memory limit from .htaccess and this problem got resolved.
I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:
php_value memory_limit 512M
After scan was over, I removed this line to make the size as it was before.
Try Using DateTime::createFromFormat
$date = DateTime::createFromFormat('d/m/Y', "24/04/2012");
echo $date->format('Y-m-d');
Output
2012-04-24
EDIT:
If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.
$old_date = explode('/', '5/4/2010');
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];
OUTPUT:
2010-4-5
Solution
Change the setup for your application, so you this parameter[-Djava.security.egd=file:/dev/../dev/urandom] next to the java command:
java -Djava.security.egd=file:/dev/../dev/urandom [your command]
a less-jquerish approach:
$('#mytable tr').each(function() {
if (!this.rowIndex) return; // skip first row
var customerId = this.cells[0].innerHTML;
});
this can obviously be changed to work with not-the-first cells.
Just do tr
delete:
tr -d "\r" <infile.txt >outfile.txt
For example, if this is a number :
ouloulou={
1:US,
2:BR,
3:FR
}
ouloulou[1]()
It's work perfectly, but if you use for example :
ouloulou[input("select 1 2 or 3"]()
it's doesn't work, because your input return string '1'. So you need to use int()
ouloulou[int(input("select 1 2 or 3"))]()
This question is old, but is missing some benchmarks. I benchmarked JOIN against its 2 competitors:
WHERE IN(...)
or equivalentThe result is clear: on MySQL, JOIN
is much faster. N+1 queries can drop the performance of an application drastically:
That is, unless you select a lot of records that point to a very small number of distinct, foreign records. Here is a benchmark for the extreme case:
This is very unlikely to happen in a typical application, unless you're joining a -to-many relationship, in which case the foreign key is on the other table, and you're duplicating the main table data many times.
Takeaway:
JOIN
See my article on Medium for more information.
This is a lightweight solution I've come across -
function E() { // Check collision
S = X - x;
D = Y - y;
F = w + W;
return (S * S + D * D <= F * F)
}
The big and small variables are of two objects, (x coordinate, y coordinate, and w width)
From here.
Updates from Bernhardt:
You can indeed do an upsert in SQLite, it just looks a little different than you are used to. It would look something like:
INSERT INTO table_name (id, column1, column2)
VALUES ("youruuid", "value12", "value2")
ON CONFLICT(id) DO UPDATE
SET column1 = "value1", column2 = "value2"
Add tomcat in Eclipse
In Eclipse, as tomcat server, double click "Tomcat v7.0 Server at Localhost", Change the properties as shown in time out settings 45 to whatever sec you like
Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure
show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.
To delete the last element of the lists, you could use:
def deleteLast(self):
if self.Ans:
del self.Ans[-1]
if self.masses:
del self.masses[-1]
In my case I need to initialise my drawer items. I fill data by below code.
val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)
// Use lambda function to add data in my custom model class i.e. DrawerItem
val drawerItems = Array<DrawerItem>(iconsArr.size, init =
{ index -> DrawerItem(iconsArr[index], names[index])})
Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)
Custom Model class-
class DrawerItem(var icon: Int, var name: String) {
}
See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:
If you want to set the xticklabels:
ax.set_xticks([1,4,5])
ax.set_xticklabels([1,4,5], fontsize=12)
If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):
ax.tick_params(axis="x", labelsize=12)
To do it all at once:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold",
horizontalalignment="left")`
It is very simple. I tried in SQL Server 2008
DELETE SUB FROM
(SELECT ROW_NUMBER() OVER (PARTITION BY EmpId, EmpName, EmpSSN ORDER BY EmpId) cnt
FROM Employee) SUB
WHERE SUB.cnt > 1
Try running fuser command
[root@guest2 ~]# fuser -mv /home
USER PID ACCESS COMMAND
/home: root 2919 f.... automount
[root@guest2 ~]# kill -9 2919
autofs
service is known to cause this issue.
You can use command
#service autofs stop
And try again.
A simple Javascript function that makes the content inside a page-element unselectable:
function makeUnselectable(elem) {
if (typeof(elem) == 'string')
elem = document.getElementById(elem);
if (elem) {
elem.onselectstart = function() { return false; };
elem.style.MozUserSelect = "none";
elem.style.KhtmlUserSelect = "none";
elem.unselectable = "on";
}
}
Here's a Perl version of the one-liner provided in the accepted answer:
git branch -r | perl -e 'while(<>) {chop; my $remote = $_; my ($local) = ($remote =~ /origin\/(.*)/); print "git branch --track $local $remote\n";}' > some-output-file
You can run the output file as a Shell script if you'd like.
We deleted our Stash project repository by accident. Fortunately someone had created a fork right before the accidental loss. I cloned the fork to my local (will omit the details of how I did that). Once I had the fork fully in my local, I ran one one-liner. I modified the remote's URL (origin in my case) to point to the target repository we were recovering to:
git remote set-url origin <remote-url>
And finally pushed all branches to origin like so:
git push --all origin
and we were back in business.
I found a tool called ttyplot
in homebrew. It's good. https://github.com/tenox7/ttyplot
From https://www.w3schools.com/css/css_boxmodel.asp
Explanation of the different parts:
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
Live example (play around by changing the values): https://www.w3schools.com/css/tryit.asp?filename=trycss_boxmodel
For the sake of completeness:
while read _ _ one _ two _; do
echo "$one $two"
done < file.txt
Instead of _
an arbitrary variable (such as junk
) can be used as well. The point is just to extract the columns.
Demo:
$ while read _ _ one _ two _; do echo "$one $two"; done < /tmp/file.txt
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495
Although BETWEEN
is easy to read and maintain, I rarely recommend its use because it is a closed interval and as mentioned previously this can be a problem with dates - even without time components.
For example, when dealing with monthly data it is often common to compare dates BETWEEN first AND last
, but in practice this is usually easier to write dt >= first AND dt < next-first
(which also solves the time part issue) - since determining last
usually is one step longer than determining next-first
(by subtracting a day).
In addition, another gotcha is that lower and upper bounds do need to be specified in the correct order (i.e. BETWEEN low AND high
).
Using Wireshark..
I have not tried this: http://wiki.wireshark.org/CaptureSetup/Loopback
If that works, you could then filter for http
/http contains GET
/http contains POST
traffic.
You might have to run two Wireshark instances, one capturing local, and one capturing remote. I'm not sure.
To both check if it exists and create if it doesn't, including intermediaries:
QDir dir("path/to/dir");
if (!dir.exists())
dir.mkpath(".");
You can increase the capacity of the stack by the following :
import sys
sys.setrecursionlimit(10000)
I solved the problem by changing my AndroidManifest.xml
.
old : <uses-permission android:name="android.permission.internet"/>
new: <uses-permission android:name="android.permission.INTERNET"/>
Another useful approach is Card Grids:
<div class="row row-cols-1 row-cols-md-2">_x000D_
<div class="col mb-4">_x000D_
<div class="card">_x000D_
<img src="..." class="card-img-top" alt="...">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col mb-4">_x000D_
<div class="card">_x000D_
<img src="..." class="card-img-top" alt="...">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col mb-4">_x000D_
<div class="card">_x000D_
<img src="..." class="card-img-top" alt="...">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col mb-4">_x000D_
<div class="card">_x000D_
<img src="..." class="card-img-top" alt="...">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
List is an Interface . You cant use List to initialize it.
List<String> supplierNames = new ArrayList<String>();
These are the some of List impelemented classes,
ArrayList, LinkedList, Vector
You could use any of this as per your requirement. These each classes have its own features.
I have had this problem Parse Error : There is a problem parsing the package.
I was testing on Android-8. I have same apk with same signature .Everything was same without the version number and version name. App was installing when I install it manually but this error occurred when I was downloading and installing updates programmatically. Then I have found my cause of problem.
There was an option to check canRequestPackageInstalls () When this method returns true then app get installed successfully. It was returning false always in my case.
So first I check this and then let the user to download and install updates.
In onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!packageManager.canRequestPackageInstalls()) {
startActivityForResult(
Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(
Uri.parse(String.format("package:%s", packageName))
), requestCodeqInstallPackage
)
} else {
canInstallPackage = true
}
}
In onActivityResult()
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
if (requestCode == requestCodeqInstallPackage && resultCode == Activity.RESULT_OK) {
if (packageManager.canRequestPackageInstalls()) {
canInstallPackage = true
}
} else {
canInstallPackage = false
Toast.makeText(mContext, "Auto update feature will not work", Toast.LENGTH_LONG)
.show()
}
}
Then when need to install update then-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if(canInstallPackage){
doInstallAppProcess()
}else{
// generate error message
}
}
Hope it will help someone.
Use forward slashes. See explanation here
@Id
@Column(name = "COLUMN_NAME", nullable = false)
public Long getId() {
return id;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = SomeCustomEntity.class)
@JoinColumn(name = "COLUMN_NAME", referencedColumnName = "COLUMN_NAME", nullable = false, updatable = false, insertable = false)
@org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.ALL)
public List<SomeCustomEntity> getAbschreibareAustattungen() {
return abschreibareAustattungen;
}
If you have already mapped a column and have accidentaly set the same values for name and referencedColumnName in @JoinColumn hibernate gives the same stupid error
Error:
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.testtest.SomeCustomEntity column: COLUMN_NAME (should be mapped with insert="false" update="false")
It's a little trickier to do what you're trying to do than I'd prefer, but that's because you don't really directly bind a DataGrid
to a DataTable
.
When you bind DataGrid.ItemsSource
to a DataTable
, you're really binding it to the default DataView
, not to the table itself. This is why, for instance, you don't have to do anything to make a DataGrid
sort rows when you click on a column header - that functionality's baked into DataView
, and DataGrid
knows how to access it (through the IBindingList
interface).
The DataView
implements IEnumerable<DataRowView>
(more or less), and the DataGrid
fills its items by iterating over this. This means that when you've bound DataGrid.ItemsSource
to a DataTable
, its SelectedItem
property will be a DataRowView
, not a DataRow
.
If you know all this, it's pretty straightforward to build a wrapper class that lets you expose properties that you can bind to. There are three key properties:
Table
, the DataTable
,Row
, a two-way bindable property of type DataRowView
, and SearchText
, a string property that, when it's set, will find the first matching DataRowView
in the table's default view, set the Row
property, and raise PropertyChanged
.It looks like this:
public class DataTableWrapper : INotifyPropertyChanged
{
private DataRowView _Row;
private string _SearchText;
public DataTableWrapper()
{
// using a parameterless constructor lets you create it directly in XAML
DataTable t = new DataTable();
t.Columns.Add("id", typeof (int));
t.Columns.Add("text", typeof (string));
// let's acquire some sample data
t.Rows.Add(new object[] { 1, "Tower"});
t.Rows.Add(new object[] { 2, "Luxor" });
t.Rows.Add(new object[] { 3, "American" });
t.Rows.Add(new object[] { 4, "Festival" });
t.Rows.Add(new object[] { 5, "Worldwide" });
t.Rows.Add(new object[] { 6, "Continental" });
t.Rows.Add(new object[] { 7, "Imperial" });
Table = t;
}
// you should have this defined as a code snippet if you work with WPF
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
// SelectedItem gets bound to this two-way
public DataRowView Row
{
get { return _Row; }
set
{
if (_Row != value)
{
_Row = value;
OnPropertyChanged("Row");
}
}
}
// the search TextBox is bound two-way to this
public string SearchText
{
get { return _SearchText; }
set
{
if (_SearchText != value)
{
_SearchText = value;
Row = Table.DefaultView.OfType<DataRowView>()
.Where(x => x.Row.Field<string>("text").Contains(_SearchText))
.FirstOrDefault();
}
}
}
public DataTable Table { get; private set; }
}
And here's XAML that uses it:
<Window x:Class="DataGridSelectionDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
xmlns:DataGridSelectionDemo="clr-namespace:DataGridSelectionDemo"
Title="DataGrid selection demo"
Height="350"
Width="525">
<Window.DataContext>
<DataGridSelectionDemo:DataTableWrapper />
</Window.DataContext>
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label>Text</Label>
<TextBox Grid.Column="1"
Text="{Binding SearchText, Mode=TwoWay}" />
</Grid>
<dg:DataGrid DockPanel.Dock="Top"
ItemsSource="{Binding Table}"
SelectedItem="{Binding Row, Mode=TwoWay}" />
</DockPanel>
</Window>
surprise to see that no have given this syntax.
.each
syntax with data or collection
jQuery.each(collection, callback(indexInArray, valueOfElement));
OR
jQuery.each( jQuery('#list option'), function(indexInArray, valueOfElement){
//your code here
});
If you want to use the new android.support.v7.app.AlertDialog and have different colors for the buttons and also have a custom layout then have a look at my https://gist.github.com/JoachimR/6bfbc175d5c8116d411e
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.custom_layout, null);
initDialogUi(v);
final AlertDialog d = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle)
.setTitle(getString(R.string.some_dialog_title))
.setCancelable(true)
.setPositiveButton(activity.getString(R.string.some_dialog_title_btn_positive),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
doSomething();
dismiss();
}
})
.setNegativeButton(activity.getString(R.string.some_dialog_title_btn_negative),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
})
.setView(v)
.create();
// change color of positive button
d.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button b = d.getButton(DialogInterface.BUTTON_POSITIVE);
b.setTextColor(getResources().getColor(R.color.colorPrimary));
}
});
return d;
}
Because it's the size of an instance of the type - presumably enum values are stored as (32-bit / 4-byte) ints here.
git push
can push all branches or a single one dependent on this configuration:
Push all branches
git config --global push.default matching
It will push all the branches to the remote branch and would merge them.
If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default
.
Push only the current branch if its named upstream is identical
git config --global push.default simple
So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.
CHAR :
VARCHAR :
any comments......!!!!
Please check the permissions on the the ca certificates installed on server.
Here is the approach I have taken to finding addresses using regular expressions:
A set of patterns is useful to find many forms that we might expect from an address starting with simply a number followed by set of strings (ex. 1 Basic Road) and then getting more specific such as looking for "P.O. Box", "c/o", "attn:", etc.
Below is a simple test in python. The test will find all the addresses but not the last 4 items which are company names. This example is not comprehensive, but can be altered to suit your needs and catch examples you find in your data.
import re
strings = [
'701 FIFTH AVE',
'2157 Henderson Highway',
'Attn: Patent Docketing',
'HOLLYWOOD, FL 33022-2480',
'1940 DUKE STREET',
'111 MONUMENT CIRCLE, SUITE 3700',
'c/o Armstrong Teasdale LLP',
'1 Almaden Boulevard',
'999 Peachtree Street NE',
'P.O. BOX 2903',
'2040 MAIN STREET',
'300 North Meridian Street',
'465 Columbus Avenue',
'1441 SEAMIST DR.',
'2000 PENNSYLVANIA AVENUE, N.W.',
'465 Columbus Avenue',
'28 STATE STREET',
'P.O, Drawer 800889.',
'2200 CLARENDON BLVD.',
'840 NORTH PLANKINTON AVENUE',
'1025 Connecticut Avenue, NW',
'340 Commercial Street',
'799 Ninth Street, NW',
'11318 Lazarro Ln',
'P.O, Box 65745',
'c/o Ballard Spahr LLP',
'8210 SOUTHPARK TERRACE',
'1130 Connecticut Ave., NW, Suite 420',
'465 Columbus Avenue',
"BANNER & WITCOFF , LTD",
"CHIP LAW GROUP",
"HAMMER & ASSOCIATES, P.C.",
"MH2 TECHNOLOGY LAW GROUP, LLP",
]
patterns = [
"c\/o [\w ]{2,}",
"C\/O [\w ]{2,}",
"P.O\. [\w ]{2,}",
"P.O\, [\w ]{2,}",
"[\w\.]{2,5} BOX [\d]{2,8}",
"^[#\d]{1,7} [\w ]{2,}",
"[A-Z]{2,2} [\d]{5,5}",
"Attn: [\w]{2,}",
"ATTN: [\w]{2,}",
"Attention: [\w]{2,}",
"ATTENTION: [\w]{2,}"
]
contact_list = []
total_count = len(strings)
found_count = 0
for string in strings:
pat_no = 1
for pattern in patterns:
match = re.search(pattern, string.strip())
if match:
print("Item found: " + match.group(0) + " | Pattern no: " + str(pat_no))
found_count += 1
pat_no += 1
print("-- Total: " + str(total_count) + " Found: " + str(found_count))
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];_x000D_
var ind = arr.findIndex(function(element){_x000D_
return element.id===2;_x000D_
})_x000D_
if(ind!==-1){_x000D_
arr.splice(ind, 1)_x000D_
}_x000D_
console.log (arr)
_x000D_
Please note that findIndex method is not supported in Internet Explorer but polyfill can be used from here
using css we can adjust specific column width which i put in below code.
user.component.css
table{
width: 100%;
}
.mat-column-username {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 28% !important;
width: 28% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
.mat-column-emailid {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 25% !important;
width: 25% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
.mat-column-contactno {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 17% !important;
width: 17% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
.mat-column-userimage {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 8% !important;
width: 8% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
.mat-column-userActivity {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 10% !important;
width: 10% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
If the reason you ask this question is because you want to use Core Bluetooth to advertise as an iBeacon rather than using the standard API, you can easily do so by advertising an NSDictionary such as:
{
kCBAdvDataAppleBeaconKey = <a7c4c5fa a8dd4ba1 b9a8a240 584f02d3 00040fa0 c5>;
}
See this answer for more information.
For me AndroPHP (its an app name) , worked perfectly... see below links
http://gntheprogrammer.blogspot.in/2013/09/how-to-use-your-android-device-as.html
Please follow the steps it will help u .....
Use collect($comments_collection)
.
Else, try json_encode($comments_collection)
to convert to json.
In simple term it can be stated as:
Spring boot = Spring MVC + Auto Configuration(Don't need to write spring.xml file for configurations) + Server(You can have embedded Tomcat, Netty, Jetty server).
And Spring Boot is an Opinionated framework, so its build taking in consideration for fast development, less time need for configuration and have a very good community support.
Old question but here's the code on how to do what you are asking. In this case I am passing data from a selected cell in a table view to another view controller.
in the .h file of the trget view:
@property(weak, nonatomic) NSObject* dataModel;
in the .m file:
@synthesize dataModel;
dataModel
can be string
, int
, or like in this case it's a model that contains many items
- (void)someMethod {
[self performSegueWithIdentifier:@"loginMainSegue" sender:self];
}
OR...
- (void)someMethod {
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
[self.navigationController pushViewController: myController animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:@"storyDetailsSegway"]) {
UITableViewCell *cell = (UITableViewCell *) sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSDictionary *storiesDict =[topStories objectAtIndex:[indexPath row]];
StoryModel *storyModel = [[StoryModel alloc] init];
storyModel = storiesDict;
StoryDetails *controller = (StoryDetails *)segue.destinationViewController;
controller.dataModel= storyModel;
}
}
This question is a duplicate of Make a div fill the height of the remaining screen space and the correct answer is to use the flexbox model.
All major browsers and IE11+ support Flexbox. For IE 10 or older, or Android 4.3 and older, you can use the FlexieJS shim.
Note how simple the markup and the CSS are. No table hacks or anything.
html, body {
height: 100%;
margin: 0; padding: 0; /* to avoid scrollbars */
}
#wrapper {
display: flex; /* use the flex model */
min-height: 100%;
flex-direction: column; /* learn more: http://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ */
}
#header {
background: yellow;
height: 100px; /* can be variable as well */
}
#body {
flex: 1;
border: 1px solid orange;
}
#footer{
background: lime;
}
<div id="wrapper">
<div id="header">Title</div>
<div id="body">Body</div>
<div id="footer">
Footer<br/>
of<br/>
variable<br/>
height<br/>
</div>
</div>
In the CSS above, the flex property shorthands the flex-grow, flex-shrink, and flex-basis properties to establish the flexibility of the flex items. Mozilla has a good introduction to the flexible boxes model.
You can parse the date using the Date
constructor, then spit out the individual time components:
function convert(str) {_x000D_
var date = new Date(str),_x000D_
mnth = ("0" + (date.getMonth() + 1)).slice(-2),_x000D_
day = ("0" + date.getDate()).slice(-2);_x000D_
return [date.getFullYear(), mnth, day].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-08"
_x000D_
As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:
function convert(str) {_x000D_
var mnths = {_x000D_
Jan: "01",_x000D_
Feb: "02",_x000D_
Mar: "03",_x000D_
Apr: "04",_x000D_
May: "05",_x000D_
Jun: "06",_x000D_
Jul: "07",_x000D_
Aug: "08",_x000D_
Sep: "09",_x000D_
Oct: "10",_x000D_
Nov: "11",_x000D_
Dec: "12"_x000D_
},_x000D_
date = str.split(" ");_x000D_
_x000D_
return [date[3], mnths[date[1]], date[2]].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-09"
_x000D_
Go to
C:\Program Files\MySQL\MySQL Server 5.2\bin
then Open MySQLInstanceConfig file
then complete the wizard.
Click finish
Solve the problem
I think this is the best way to change the port number also.
It works for me
you can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
All these answers seem like heavy lifting...
I just created a .env
file; edited my bootstrap/app.php
file, and uncommented the following line...
Dotenv::load(__DIR__.'/../');
Hope this helps someone
According to Jean-Paul Calderone's Filesystem structure of a Python project:
Project/
|-- bin/
| |-- project
|
|-- project/
| |-- test/
| | |-- __init__.py
| | |-- test_main.py
| |
| |-- __init__.py
| |-- main.py
|
|-- setup.py
|-- README
While you are in debug mode within the catch {...}
block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:
((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors
This will allow you to drill down into the ValidationErrors
tree. It's the easiest way I've found to get instant insight into these errors.
For Visual 2012+ users who care only about the first error and might not have a catch
block, you can even do:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors.First().ValidationErrors.First().ErrorMessage
In my case, it was the open_basedir which was defined. I commented it out (default) and my issue was resolved. I can now set the upload directory anywhere.
While calling/invoking your programme you can use this command : java [-options] className [args...]
in place of [-options] provide more memory e.g -Xmx1024m or more. but this is just a workaround, u have to change ur parsing mechanism.
In my case, I had to remove the previous versions first and download the latest one instead. v1.0 stable was released on Feb 23rd.
Following the answer of @Even Mien I have tried to go a bit further and make it Generic, I seem to be almost there but one case still resist and I probably can simplify my code a bit.
I post it here if anyone see how I could improve and especially make it works as I can't assign it from a string
So Far I have the following results:
Console.WriteLine(TestEnum.Test1);//displays "TEST1"
bool test = "TEST1" == TestEnum.Test1; //true
var test2 = TestEnum.Test1; //is TestEnum and has value
string test3 = TestEnum.Test1; //test3 = "TEST1"
var test4 = TestEnum.Test1 == TestEnum.Test2; //false
EnumType<TestEnum> test5 = "TEST1"; //works fine
//TestEnum test5 = "string"; DOESN'T compile .... :(:(
Where the magics happens :
public abstract class EnumType<T> where T : EnumType<T>
{
public string Value { get; set; }
protected EnumType(string value)
{
Value = value;
}
public static implicit operator EnumType<T>(string s)
{
if (All.Any(dt => dt.Value == s))
{
Type t = typeof(T);
ConstructorInfo ci = t.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,null, new Type[] { typeof(string) }, null);
return (T)ci.Invoke(new object[] {s});
}
else
{
return null;
}
}
public static implicit operator string(EnumType<T> dt)
{
return dt?.Value;
}
public static bool operator ==(EnumType<T> ct1, EnumType<T> ct2)
{
return (string)ct1 == (string)ct2;
}
public static bool operator !=(EnumType<T> ct1, EnumType<T> ct2)
{
return !(ct1 == ct2);
}
public override bool Equals(object obj)
{
try
{
return (string)obj == Value;
}
catch
{
return false;
}
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public static IEnumerable<T> All
=> typeof(T).GetProperties()
.Where(p => p.PropertyType == typeof(T))
.Select(x => (T)x.GetValue(null, null));
}
I only then have to declare this for my enums:
public class TestEnum : EnumType<TestEnum>
{
private TestEnum(string value) : base(value)
{}
public static TestEnum Test1 { get { return new TestEnum("TEST1"); } }
public static TestEnum Test2 { get { return new TestEnum("TEST2"); } }
}
I'd like to supplement BalusC's answer with the mapping rules and an example.
Mapping rules from Servlet 2.5 specification:
In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello
To map http://host:port/context/hello.jsp
AWS added a new feature to connect to instance without any open port, the AWS SSM Session Manager. https://aws.amazon.com/blogs/aws/new-session-manager/
I've created a neat SSH ProxyCommand script that temporary adds your public ssh key to target instance during connection to target instance. The nice thing about this is you will connect without the need to add the ssh(22) port to your security groups, because the ssh connection is tunneled through ssm session manager.
AWS SSM SSH ProxyComand -> https://gist.github.com/qoomon/fcf2c85194c55aee34b78ddcaa9e83a1
Note: The last line is mandatory.
If we didn't specify Access-Control-Expose-Headers, we will not get File Name in UI.
FileInfo file = new FileInfo(FILEPATH);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = file.Name
};
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
We can change the cookie time session feature at:
Settings->Features->General->Login cookie validity
I found the answer in here.. No activity within 1440 seconds; please log in again
EDIT:
This solution will work only for the current session, to change permanently do:
open config.inc.php in the root phpMyAdmin directory .
wamp folder: wamp\apps\phpmyadmin{version}\config.inc.php
ubuntu: /etc/phpmyadmin
add this line
$cfg['LoginCookieValidity'] = <your_timeout>;
Example
$cfg['LoginCookieValidity'] = '144000';
A vector is a container class while an array is an allocated memory.
EDIT (removed wrong solution). EDIT (to add this other option):
Another way to use it would be subclass QThread since it has protected *sleep methods.
QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);
Here's the code to create your own *sleep method.
#include <QThread>
class Sleeper : public QThread
{
public:
static void usleep(unsigned long usecs){QThread::usleep(usecs);}
static void msleep(unsigned long msecs){QThread::msleep(msecs);}
static void sleep(unsigned long secs){QThread::sleep(secs);}
};
and you call it by doing this:
Sleeper::usleep(10);
Sleeper::msleep(10);
Sleeper::sleep(10);
This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.
To uninstalling existing MongoDB packages. I think this link will helpful.
Use ps
to find the process id for the application, then use top -p1010
(substitute 1010 for the real process id).
The RES column is the used physical memory and the VIRT column is the used virtual memory - including libraries and swapped memory.
More info can be found using "man top"
I just want to add that this nearly identical post provides the very useful alternative of using an echo pipe if no force or quiet switch is available. For instance, I think it's the only way to bypass the Y/N prompt in this example.
Echo y|NETDOM COMPUTERNAME WorkComp /Add:Work-Comp
In a general sense you should first look at your command switches for /f, /q, or some variant thereof (for example, Netdom RenameComputer uses /Force, not /f). If there is no switch available, then use an echo pipe.
Depending on the hibernate flush mode that you are using (AUTO
is the default) save
may or may not write your changes to the DB straight away. When you call saveAndFlush
you are enforcing the synchronization of your model state with the DB.
If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save()
and saveAndFlush()
because the select triggers a flush first. See the documention.
If you're targeting iOS 11.0+ / macOS 10.13+, you simply use ISO8601DateFormatter
with the withInternetDateTime
and withFractionalSeconds
options, like so:
let date = Date()
let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let string = iso8601DateFormatter.string(from: date)
// string looks like "2020-03-04T21:39:02.112Z"
I didn't find the Dynamic Web Module option when I clicked on the link, then I have installed Maven(Java EE) Integration for Eclipse WTP from the Eclipse Marketplace.Then, the above steps worked.
Code for Find the Column Name same as using the Like
in sql.
foreach (DataGridViewColumn column in GrdMarkBook.Columns)
//GrdMarkBook is Data Grid name
{
string HeaderName = column.HeaderText.ToString();
// This line Used for find any Column Have Name With Exam
if (column.HeaderText.ToString().ToUpper().Contains("EXAM"))
{
int CoumnNo = column.Index;
}
}
As metioned by nixxx adding ob_start()
before adding any php code will prevent the headers already sent error.
It worked for me
The code below also works. But it first loads the page and then redirects when I use it.
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$redirect_url.'">';
Without function here it is...it works fine with listArrays filled with Objects
example `
al.add(new Student(101,"Jack",23,'C'));//adding Student class object
al.add(new Student(102,"Evan",21,'A'));
al.add(new Student(103,"Berton",25,'B'));
al.add(0, new Student(104,"Brian",20,'D'));
al.add(0, new Student(105,"Lance",24,'D'));
for(int i = 101; i< 101+al.size(); i++) {
al.get(i-101).rollno = i;//rollno is 101, 102 , 103, ....
}
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
Other answers were not working when I put setResult
in onBackPressed
. Commenting call to super onBackPressed
and calling finish
manually solves the problem:
@Override
public void onBackPressed() {
//super.onBackPressed();
Intent i = new Intent();
i.putExtra(EXTRA_NON_DOWNLOADED_PAGES, notDownloaded);
setResult(RESULT_OK, i);
finish();
}
And in first activity:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == QUEUE_MSG) {
if (resultCode == RESULT_OK) {
Serializable tmp = data.getSerializableExtra(MainActivity.EXTRA_NON_DOWNLOADED_PAGES);
if (tmp != null)
serializable = tmp;
}
}
}