Below works for first tr
of the table under thead
table thead tr:first-child {
background: #f2f2f2;
}
And this works for the first tr
of thead
and tbody
both:
table thead tbody tr:first-child {
background: #f2f2f2;
}
I've had this happen on VS after I changed the file's line endings. Changing them back to Windows CR LF fixed the issue.
Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.
That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...
What version of the SQL Server engine do you get from SELECT @@VERSION
??
I ran into a similar issue where I wanted to call a function defined in my controller from my view. Although it perplexed me for a while trying to figure out how to get to the controller from the view it turned out to be fairly straightforward.
I hand off an array to my views with data records that the view formats and presents to the user with jQuery DataTables (big duh). One column in the presented UI table is a set of action buttons that need to be created per row based on the content of the data in each of the rows. I guess I could have added the button definitions to the data rows as a column sent to the views but not all views needed the buttons so why? Instead, I wanted the view that needed them add them.
In the controller I pass a reference to the controller itself to the view as in
->with('callbackController', $this)
I called it callbackController as that is what I was doing. Now, inside my view I can either escape to PHP to use $callbackController to access the parent controller as in
<?php echo $callbackController->makeButtons($parameters); ?>
or just use the Blade mechanism
{!! $callbackController->makeButtons($parameters); ?>
It seems to be working fine across multiple controllers and views. I have not noticed a performance penalty using this mechanism and I have one huge table with over 50K rows.
I have not tried to pass on references to other objects (e.g., models, etc) yet but I do not see what that would not work as well
Might not be elegant but it seems to get the job done.
The right way is to fix the overflow, but....
You can give yourself a bigger stack:-
using System.Threading;
Thread T = new Thread(threadDelegate, stackSizeInBytes);
T.Start();
You can use System.Diagnostics.StackTrace FrameCount property to count the frames you've used and throw your own exception when a frame limit is reached.
Or, you can calculate the size of the stack remaining and throw your own exception when it falls below a threshold:-
class Program
{
static int n;
static int topOfStack;
const int stackSize = 1000000; // Default?
// The func is 76 bytes, but we need space to unwind the exception.
const int spaceRequired = 18*1024;
unsafe static void Main(string[] args)
{
int var;
topOfStack = (int)&var;
n=0;
recurse();
}
unsafe static void recurse()
{
int remaining;
remaining = stackSize - (topOfStack - (int)&remaining);
if (remaining < spaceRequired)
throw new Exception("Cheese");
n++;
recurse();
}
}
Just catch the Cheese. ;)
Biginteger
is an immutable class.
You need to explicitly assign value of your output to sum like this:
sum = sum.add(BigInteger.valueof(i));
This site explain step by step that what you need to do Certificates, Identifiers & Profiles and as your question
"Valid Signing identity not found"?
You need the private key that were used to sign the code base with provisioning profile. . If you don't have then you can generate a new signing request on the iOS developer portal.
For Export:
Xcode -> Organizer, select your team. Click Export. Specify a filename and a password, and click Save.`
For Import:
Xcode -> Organizer, select your team. Click Import. Select the file containing your code signing assets. Enter the password for the file, and click Open.
System.out
is just an instance of PrintStream
. You can check its JavaDoc. Its variability is based on method overloading (multiple methods with the same name, but with different parameters).
This print stream is sending its output to so called standard output.
In your question you mention a technique called variadic functions (or varargs). Unfortunately that is not supported by PrintStream#print
, so you must be mistaking this with something else. However it is very easy to implement these in Java. Just check the documentation.
And if you are curious how Java knows how to concatenate non-string variables "foo" + 1 + true + myObj
, it is mainly responsibility of a Java compiler.
When there is no variable involved in the concatenation, the compiler simply concatenates the string. When there is a variable involved, the concatenation is translated into StringBuilder#append
chain. There is no concatenation instruction in the resulting byte code; i.e. the +
operator (when talking about string concatenation) is resolved during the compilation.
All types in Java can be converted to string (int
via methods in Integer
class, boolean
via methods in Boolean
class, objects via their own #toString
, ...). You can check StringBuilder's source code if you are interested.
UPDATE: I was curious myself and checked (using javap) what my example System.out.println("foo" + 1 + true + myObj)
compiles into. The result:
System.out.println(new StringBuilder("foo1true").append(myObj).toString());
"an object" of what type?
You can certainly assign NULL
(and nullptr
) to objects of pointer types, and it is implementation defined if you can assign NULL
to objects of arithmetic types.
If you mean objects of some class type, the answer is NO (excepting classes that have operator=
accepting pointer or arithmetic types)
"empty" is more plausible, as many types have both copy assignment and default construction (often implicitly). To see if an existing object is like a default constructed one, you will also need an appropriate bool operator==
You are actually trying to redirect a page which has some response to throw. So first you keep the information you have throw in a buffer using response.buffer = true
in beginning of the page and then flush it when required using response.flush
this error will get fixed
You can also use the standard CSS way (no need for JQuery plugin, but compatible with all browsers):
// Start blinking
$(".myblink").css("text-decoration", "blink");
// Stop blinking
$(".myblink").css("text-decoration", "none");
Note: I found this question looking for one of the steps in the answer to how to resize an existing array.
So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.
For anyone else finding this question looking for the same thing I was, it is very simple:
Array.Resize<T>(ref arrayVariable, newSize);
where T is the type, i.e. where arrayVariable is declared:
T[] arrayVariable;
That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.
See the MSDN article for more.
Fragment: Make a BaseFragment placing a method:
public boolean onBackPressed();
Activity:
@Override
public void onBackPressed() {
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (!fragment.isVisible()) continue;
if (fragment instanceof BaseFragment && ((BaseFragment) fragment).onBackPressed()) {
return;
}
}
}
super.onBackPressed();
}
Your activity will run over the attached and visible fragments and call onBackPressed() on each one of them and abort if one of them returns 'true' (meaning that it has been handled, so no further actions).
If you happen to be using a mac keyboard on linux (ubuntu), Insert
is actually fn
+ return
. You can also click on the zero of the number pad to switch between the cursor types.
Took me a while to figure that out. :-P
In my instance, I was running an abnormal query to fix data. If you lock the tables in your query, then you won't have to deal with the Lock timeout:
LOCK TABLES `customer` WRITE;
update customer set account_import_id = 1;
UNLOCK TABLES;
This is probably not a good idea for normal use.
For more info see: MySQL 8.0 Reference Manual
The documentation from Github is really explanatory.
https://help.github.com/en/articles/adding-a-new-ssh-key-to-your-github-account https://help.github.com/en/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
I think you must do the lasts steps from the guide to proper configure your keys
$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/id_rsa
Add & Remove Classes (tested on IE8+)
Add trim() to IE (taken from: .trim() in JavaScript not working in IE)
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
Add and Remove Classes:
function addClass(element,className) {
var currentClassName = element.getAttribute("class");
if (typeof currentClassName!== "undefined" && currentClassName) {
element.setAttribute("class",currentClassName + " "+ className);
}
else {
element.setAttribute("class",className);
}
}
function removeClass(element,className) {
var currentClassName = element.getAttribute("class");
if (typeof currentClassName!== "undefined" && currentClassName) {
var class2RemoveIndex = currentClassName.indexOf(className);
if (class2RemoveIndex != -1) {
var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
var updatedClassName = currentClassName.replace(class2Remove,"").trim();
element.setAttribute("class",updatedClassName);
}
}
else {
element.removeAttribute("class");
}
}
Usage:
var targetElement = document.getElementById("myElement");
addClass(targetElement,"someClass");
removeClass(targetElement,"someClass");
A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/
First of all, set more safe initial data:
getInitialState : function() {
return {data: {comments:[]}};
},
And ensure your ajax data.
It should work if you follow above two instructions like Demo.
Updated: you can just wrap the .map block with conditional statement.
if (this.props.data) {
var commentNodes = this.props.data.map(function (comment){
return (
<div>
<h1>{comment.author}</h1>
</div>
);
});
}
Try this code
document.onreadystatechange = function () {
if (document.readyState == "interactive") {
initApplication();
}
}
visit https://developer.mozilla.org/en-US/docs/DOM/document.readyState for more details
.offset()
will return the offset position of an element as a simple object, eg:
var position = $(element).offset(); // position = { left: 42, top: 567 }
You can use this return value to position other elements at the same spot:
$(anotherElement).css(position)
Solution for change TextView
width to wrap content.
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.requestLayout();
// Call requestLayout() for redraw your TextView when your TextView is already drawn (laid out) (eg: you update TextView width when click a Button).
// If your TextView is drawing you may not need requestLayout() (eg: you change TextView width inside onCreate()). However if you call it, it still working well => for easy: always use requestLayout()
// Another useful example
// textView.getLayoutParams().width = 200; // For change `TextView` width to 200 pixel
I sometimes find a variation of this useful.
Example in JavaScript:
class Scaler {
constructor(inMin, inMax, outMin, outMax) {
this.inMin = inMin;
this.inMax = inMax;
this.outMin = outMin;
this.outMax = outMax;
}
scale(value) {
const result = (value - this.inMin) * (this.outMax - this.outMin) / (this.inMax - this.inMin) + this.outMin;
if (result < this.outMin) {
return this.outMin;
} else if (result > this.outMax) {
return this.outMax;
}
return result;
}
}
This example along with a function based version comes from the page https://writingjavascript.com/scaling-values-between-two-ranges
Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.
Meanwhile you have to use double quotes not single quote to expand variables:
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
Semicolons at the end of a single command are also unnecessary.
So far:
#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
For su
you can run it with:
su -c 'sh /path/to/script.sh'
Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using .
or source
from the interactive shell. It could have been a standalone scipt, or it could have been source
'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.
Open the application/config/config.php file and make the changes given below,
set your base url by replacing the value of $config['base_url']
, as
$config['base_url'] = 'http://localhost/YOUR_PROJECT_DIR_NAME';
make the $config['index_page']
configuration to empty as $config['index_page'] = '';
Create new .htaccess file in project root folder and use the given settings,
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|assets|images|js|css|uploads|favicon.png|favicon.ico|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
Restart the server, open the project and you'll be good to go.
The answer below is apparently obsolete now, but works with older drivers. See comments.
If you have the connection string you could also use MongoDatabase directly:
var db = MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");
You could also do that:
In package.json
:
"scripts": {
"cool": "./cool.js"
}
In cool.js
:
console.log({ myVar: process.env.npm_config_myVar });
In CLI:
npm --myVar=something run-script cool
Should output:
{ myVar: 'something' }
Update: Using npm 3.10.3, it appears that it lowercases the process.env.npm_config_
variables? I'm also using better-npm-run
, so I'm not sure if this is vanilla default behavior or not, but this answer is working. Instead of process.env.npm_config_myVar
, try process.env.npm_config_myvar
Here's a plain Javascript way of doing toggle:
<script>
var toggle = function() {
var mydiv = document.getElementById('newpost');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">
A rather roundabout way, just for completeness:
for /f "delims=" %i in ('type CON') do set inp=%i
Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.
Robust crop with opencv copy border function:
def imcrop(img, bbox):
x1, y1, x2, y2 = bbox
if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
return img[y1:y2, x1:x2, :]
def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
img = cv2.copyMakeBorder(img, - min(0, y1), max(y2 - img.shape[0], 0),
-min(0, x1), max(x2 - img.shape[1], 0),cv2.BORDER_REPLICATE)
y2 += -min(0, y1)
y1 += -min(0, y1)
x2 += -min(0, x1)
x1 += -min(0, x1)
return img, x1, x2, y1, y2
You can play with delay
prop of animation, just set visibility:visible
after a delay, demo:
@keyframes delayedShow {_x000D_
to {_x000D_
visibility: visible;_x000D_
}_x000D_
}_x000D_
_x000D_
.delayedShow{_x000D_
visibility: hidden;_x000D_
animation: 0s linear 2.3s forwards delayedShow ;_x000D_
}
_x000D_
So, Where are you?_x000D_
_x000D_
<div class="delayedShow">_x000D_
Hey, I'm here!_x000D_
</div>
_x000D_
I've created a dynamic way to call each event automatically. It perfect to focus a field, because it call the event just once, removing it after use.
function modalEvents() {
var modal = $('#modal');
var events = ['show', 'shown', 'hide', 'hidden'];
$(events).each(function (index, event) {
modal.on(event + '.bs.modal', function (e) {
var callback = modal.data(event + '-callback');
if (typeof callback != 'undefined') {
callback.call();
modal.removeData(event + '-callback');
}
});
});
}
You just need to call modalEvents()
on document ready.
Use:
$('#modal').data('show-callback', function() {
$("input#photo_name").focus();
});
So, you can use the same modal to load what you want without worry about remove events every time.
For more info on this click here.
Example
<div id="header_id" class="header_class">Text</div>
#header_id {font-color:#fff}
.header_class {font-color:#000}
(Note that CSS uses the prefix # for IDs and . for Classes.)
However color
was an HTML 4.01 <font>
tag attribute deprecated in HTML 5.
In CSS there is no "font-color", the style is color
so the above should read:
Example
<div id="header_id" class="header_class">Text</div>
#header_id {color:#fff}
.header_class {color:#000}
The text would be white.
This notation (first seen here) looks useful too:
insert into postagem (
resumopostagem,
textopostagem,
dtliberacaopostagem,
idmediaimgpostagem,
idcatolico,
idminisermao,
idtipopostagem
) select
resumominisermao,
textominisermao,
diaminisermao,
idmediaimgminisermao,
idcatolico ,
idminisermao,
1
from
minisermao
Check out: http://commons.apache.org/io/
It has copy, and as stated the JDK already has move.
Don't implement your own copy method. There are so many floating out there...
After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,
client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
There is a relatively simple implementation of in-place merge sort using Kronrod's original technique but with simpler implementation. A pictorial example that illustrates this technique can be found here: http://www.logiccoder.com/TheSortProblem/BestMergeInfo.htm.
There are also links to more detailed theoretical analysis by the same author associated with this link.
This may help someone visiting this question.
I had an issue where it was slow only in very large files. When opening braces such as {
or after completing a type, such as decimal
it would hang.
This was resolved by disabling the "Show a completion list after every character is typed" setting in Options => Text Editor => C# => Intellisense
If you're trying to print()
Unicode, and getting ascii codec errors, check out this page, the TLDR of which is do export PYTHONIOENCODING=UTF-8
before firing up python (this variable controls what sequence of bytes the console tries to encode your string data as). Internally, Python3 uses UTF-8 by default (see the Unicode HOWTO) so that's not the problem; you can just put Unicode in strings, as seen in the other answers and comments. It's when you try and get this data out to your console that the problem happens. Python thinks your console can only handle ascii. Some of the other answers say, "Write it to a file, first" but note they specify the encoding (UTF-8) for doing so (so, Python doesn't change anything in writing), and then use a method for reading the file that just spits out the bytes without any regard for encoding, which is why that works.
document.getElementsByName("iframe_name")[0].contentWindow.document.body.focus();
Personal preference.
Usually. Sometimes it matters but, not to seem like a jerk here, but if you have to ask, it probably doesn't.
You can use Object.assign()
to merge them into a new object:
const response = {_x000D_
lat: -51.3303,_x000D_
lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
id: 'qwenhee-9763ae-lenfya',_x000D_
address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = Object.assign({}, item, { location: response });_x000D_
_x000D_
console.log(newItem );
_x000D_
You can also use object spread, which is a Stage 4 proposal for ECMAScript:
const response = {_x000D_
lat: -51.3303,_x000D_
lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
id: 'qwenhee-9763ae-lenfya',_x000D_
address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well_x000D_
_x000D_
console.log(newItem );
_x000D_
constructor(
public sanitizer: DomSanitizer, ) {
}
I had been struggling for 4 hours. the problem was in img tag. When you use square bracket to 'src' ex: [src]. you can not use this angular expression {{}}. you just give directly from an object example below. if you give angular expression {{}}. you will get interpolation error.
first i used ngFor to iterate the countries
*ngFor="let country of countries"
second you put this in the img tag. this is it.
<img [src]="sanitizer.bypassSecurityTrustResourceUrl(country.flag)"
height="20" width="20" alt=""/>
Another approach can be taken into account
library(stringr)
str_replace_all(" xx yy 11 22 33 ", regex("\\s*"), "")
#[1] "xxyy112233"
\\s: Matches Space, tab, vertical tab, newline, form feed, carriage return
*: Matches at least 0 times
If you installed the SquashFS image you can run the script firstboot
. That will return OpenWrt to the defaults of when you flashed the router.
With your serial access just run firstboot and then power cycle the device.
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
While pip install might work. Please check the project structure and see if there is no virtual environment already (It is a good practice to have one) created in the project. If there is, activate it with source <name_of_virtual_env>/bin/activate
(for MacOS) and venv\Scripts\Activate.ps1
(for Windows powershell) or venv\Scripts\activate.bat
(for Windows cmd). then pip install selenium into the environment.
If it isn't,
check if you have a virtual environment with virtualenv --version
If it displays an error, install it with pip install virtualenv
then create a virtual environment with
virtualenv <name_of_virtual_env>
(Both Windows and MacOS)or
python -m venv <name_of_virtual_env>
(Windows Only)
then activate the virtual environment
with
source <name_of_virtual_env>/bin/activate
(for MacOS) and
venv\Scripts\Activate.ps1
(for Windows powershell) or
venv\Scripts\activate.bat
(for Windows cmd).
then install selenium with pip install -U selenium (it will install the latest version).
If it doesn't display an error, just create a virtual environment in the project, activate it and install selenium inside of it.
This is because your string does not strictly contain the integers in string format. It has alphanumeric chars in it.
I had this problem after upgrading to PHP5.6. My answer is very similar to Adriano's, except I had to run:
sudo apt-get install php5.6-curl
Notice the "5.6". Installing php5-curl didn't work for me.
You could use JavaScript and trigger the hidden file input when the button input has been clicked.
http://jsfiddle.net/gregorypratt/dhyzV/ - simple
http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery
Or, you could style a div directly over the file input and set pointer-events
in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events
Did you try showing your window using the ShowDialog method?
Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.
Best thing is
File.AppendAllText("c:\\file.txt","Your Text");
This is more likely to get you what you want:
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
If you want to know the location of you NPM packages, you should:
which npm // locate a program file in the user's path SEE man which
// OUTPUT SAMPLE
/usr/local/bin/npm
la /usr/local/bin/npm // la: aliased to ls -lAh SEE which la THEN man ls
lrwxr-xr-x 1 t04435 admin 46B 18 Sep 10:37 /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js
So given that npm is a NODE package itself, it is installed in the same location as other packages(EUREKA). So to confirm you should cd into node_modules and list the directory.
cd /usr/local/lib/node_modules/
ls
#SAMPLE OUTPUT
@angular npm .... all global npm packages installed
npm root -g
As per @anthonygore 's comment
In general, interfaces are used only in languages that use the single-inheritance class model. In these single-inheritance languages, interfaces are typically used if any class could use a particular method or set of methods. Also in these single-inheritance languages, abstract classes are used to either have defined class variables in addition to none or more methods, or to exploit the single-inheritance model to limit the range of classes that could use a set of methods.
Languages that support the multiple-inheritance model tend to use only classes or abstract base classes and not interfaces. Since Python supports multiple inheritance, it does not use interfaces and you would want to use base classes or abstract base classes.
In case you want to apply the shadow to the inside of the element (inset
) but only want it to appear on one single side you can define a negative value to the "spread" parameter (5th parameter in the second example).
To completely remove it, make it the same size as the shadows blur (4th parameter in the second example) but as a negative value.
Also remember to add the offset to the y-position (3rd parameter in the second example) so that the following:
box-shadow: inset 0px 4px 3px rgba(50, 50, 50, 0.75);
becomes:
box-shadow: inset 0px 7px 3px -3px rgba(50, 50, 50, 0.75);
Check this updated fiddle: http://jsfiddle.net/FrEnY/1282/ and more on the box-shadow parameters here: http://www.w3schools.com/cssref/css3_pr_box-shadow.asp
You can try this:
int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
this.Controls.Add(txt);
txt.Top = cleft * 40;
txt.Size = new Size(200, 16);
txt.Left = 150;
cleft = cleft + 1;
Label lbl = new Label();
this.Controls.Add(lbl);
lbl.Top = aleft * 40;
lbl.Size = new Size(100, 16);
lbl.ForeColor = Color.Blue;
lbl.Text = "BoxNo/CardNo";
lbl.Left = 70;
aleft = aleft + 1;
return;
}
private void btd_Click(object sender, EventArgs e)
{
//Here you Delete Text Box One By One(int ix for Text Box)
for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
//Here you Delete Lable One By One(int ix for Lable)
for (int x = this.Controls.Count - 2; x >= 0; x--)
{
if (this.Controls[ix] is TextBox)
this.Controls[ix].Dispose();
if (this.Controls[x] is Label)
this.Controls[x].Dispose();
return;
}
}
I have the similar problem but when I tried to remove the datatype:'json' I still have the problem. My error is executing instead of the Success
function cmd(){
var data = JSON.stringify(display1());
$.ajax({
type: 'POST',
url: '/cmd',
contentType:'application/json; charset=utf-8',
//dataType:"json",
data: data,
success: function(res){
console.log('Success in running run_id ajax')
//$.ajax({
// type: "GET",
// url: "/runid",
// contentType:"application/json; charset=utf-8",
// dataType:"json",
// data: data,
// success:function display_runid(){}
// });
},
error: function(req, err){ console.log('my message: ' + err); }
});
}
useState() is an example built-in React hook that lets you use states in your functional components. This was not possible before React 16.7.
The useState function is a built in hook that can be imported from the react package. It allows you to add state to your functional components. Using the useState hook inside a function component, you can create a piece of state without switching to class components.
None of the extensions worked for me, so I installed a simple local proxy. In my case https://www.npmjs.com/package/local-cors-proxy It is a 2-minute setup:
(from their site)
npm install -g local-cors-proxy
API endpoint that we want to request that has CORS issues:
https://www.yourdomain.ie/movies/list
Start Proxy:
lcp --proxyUrl https://www.yourdomain.ie
Then in your client code, new API endpoint:
http://localhost:8010/proxy/movies/list
Worked like a charm for me: your app calls the proxy, who calls the server. Zero CORS problems.
Or, you could do it the really simple way.
Dim OpenCMD
OpenCMD = CreateObject("wscript.shell")
OpenCMD.run("Command Goes Here")
Remove the library from your Podfile
Run pod install
on the terminal
I Know it's late but this may help, this is an example how I write custom adapter class for different click actions
public class CustomAdapter extends BaseAdapter {
TextView title;
Button button1,button2;
public long getItemId(int position) {
return position;
}
public int getCount() {
return mAlBasicItemsnav.size(); // size of your list array
}
public Object getItem(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.listnavsub_layout, null, false); // use sublayout which you want to inflate in your each list item
}
title = (TextView) convertView.findViewById(R.id.textViewnav); // see you have to find id by using convertView.findViewById
title.setText(mAlBasicItemsnav.get(position));
button1=(Button) convertView.findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//your click action
// if you have different click action at different positions then
if(position==0)
{
//click action of 1st list item on button click
}
if(position==1)
{
//click action of 2st list item on button click
}
});
// similarly for button 2
button2=(Button) convertView.findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//your click action
});
return convertView;
}
}
for more information on How to create Circle Android Custom Progress Bar view this link
Step 01 You should create an xml file on drawable file for configure the appearance of progress bar . So Im creating my xml file as circular_progress_bar.xml.
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="120"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="140">
<item android:id="@android:id/background">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:useLevel="false"
android:angle="0"
android:type="sweep"
android:thicknessRatio="50.0">
<solid android:color="#000000"/>
</shape>
</item>
<item android:id="@android:id/progress">
<rotate
android:fromDegrees="120"
android:toDegrees="120">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:angle="0"
android:type="sweep"
android:thicknessRatio="50.0">
<solid android:color="#ffffff"/>
</shape>
</rotate>
</item>
</layer-list>
Step 02 Then create progress bar on your xml file Then give the name of xml file on your drawable folder as the parth of android:progressDrawable
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginLeft="0dp"
android:layout_centerHorizontal="true"
android:indeterminate="false"
android:max="100"
android:progressDrawable="@drawable/circular_progress_bar" />
Step 03 Visual the progress bar using thread
package com.example.progress;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private ProgressBar progBar;
private TextView text;
private Handler mHandler = new Handler();
private int mProgressStatus=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progBar= (ProgressBar)findViewById(R.id.progressBar);
text = (TextView)findViewById(R.id.textView1);
dosomething();
}
public void dosomething() {
new Thread(new Runnable() {
public void run() {
final int presentage=0;
while (mProgressStatus < 63) {
mProgressStatus += 1;
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progBar.setProgress(mProgressStatus);
text.setText(""+mProgressStatus+"%");
}
});
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
int min = 65;
int max = 80;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Note that nextInt(int max)
returns an int
between 0 inclusive and max exclusive. Hence the +1
.
datagridview1.Rows[0].HeaderCell.Value = "Your text";
It works.
public class NumberFormatExceptionExample {
private static final String str = "123.234";
public static void main(String[] args){
float i = Float.valueOf(str); //Float.parseFloat(str);
System.out.println("Value parsed :"+i);
}
}
This should resolve the problem.
Can anyone suggest how should we handle this when the string comes in 35,000.00
You are correct about the action used in Intent but it's not the only thing you have to do. You'll also have to add
startActivityForResult(intent, YOUR_REQUEST_CODE);
To get it all done and retrieve the actual picture you could check the following thread.
I wanted to remove the too-much spaces in a string (also in between the string, not only in the beginning or end). I made this, because I don't know how to do it otherwise:
string = "Name : David Account: 1234 Another thing: something "
ready = False
while ready == False:
pos = string.find(" ")
if pos != -1:
string = string.replace(" "," ")
else:
ready = True
print(string)
This replaces double spaces in one space until you have no double spaces any more
This worked for me:
<script>
jQuery.noConflict();
// Use jQuery via jQuery() instead of via $()
jQuery(document).ready(function(){
jQuery("div").hide();
});
</script>
Reason: "Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $".
Read full reason here: https://api.jquery.com/jquery.noconflict/
If this solves your issue, it's likely another library is also using $.
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the dns for the domain e.g
mydomain.com has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain
anothersite.mydomain.com
of which the site is actually on another server then
login to Godaddy and add an A record dnsimple anothersite.mydomain.com and point the IP to the other server 98.22.11.11
And that's it.
Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.
In my case this amounted to defining my column as:
`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''
This is in my opinion preferential to adjusting your queries.
This warning generated for default ASP.NET MVC 4 beta see here
In, any cast this Warning can be eliminated by manually editing the .csproj file for your project.
modify........: Reference Include="System.Net.Http"
to read ......: Reference Include="System.Net.Http, Version=4.0.0.0"
The parent of the row is not the object you think, this is what I understand from the error.
Try detecting the parent of the row first, then you can be sure what to write into getElementById
part of the parent.
I had the same problem. Check out the comment in https://gist.github.com/khernyo/4226923#comment-812526
It says:
for gradle android plugin v0.3 use "com.android.build.gradle.tasks.PackageApplication"
That should fix your problem.
Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:
You should use the flag --gtest_filter
, like
--gtest_filter=Test_Cases1*
(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)
You should set the variable GTEST_FILTER
like
export GTEST_FILTER = "Test_Cases1*"
You should set a flag filter
, like
::testing::GTEST_FLAG(filter) = "Test_Cases1*";
such that your main function becomes something like
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
::testing::GTEST_FLAG(filter) = "Test_Cases1*";
return RUN_ALL_TESTS();
}
See section Running a Subset of the Tests for more info on the syntax of the string you can use.
Using list comprehensions in python, you can collect an entire column of values into a list using just two lines:
df = sqlContext.sql("show tables in default")
tableList = [x["tableName"] for x in df.rdd.collect()]
In the above example, we return a list of tables in database 'default', but the same can be adapted by replacing the query used in sql().
Or more abbreviated:
tableList = [x["tableName"] for x in sqlContext.sql("show tables in default").rdd.collect()]
And for your example of three columns, we can create a list of dictionaries, and then iterate through them in a for loop.
sql_text = "select name, age, city from user"
tupleList = [{name:x["name"], age:x["age"], city:x["city"]}
for x in sqlContext.sql(sql_text).rdd.collect()]
for row in tupleList:
print("{} is a {} year old from {}".format(
row["name"],
row["age"],
row["city"]))
Thread.stop is deprecated so how do we stop a thread in java ?
Always use interrupt method and future to request cancellation
Callable < String > callable = new Callable < String > () {
@Override
public String call() throws Exception {
String result = "";
try {
//assume below take method is blocked as no work is produced.
result = queue.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return result;
}
};
Future future = executor.submit(callable);
try {
String result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
logger.error("Thread timedout!");
return "";
} finally {
//this will call interrupt on queue which will abort the operation.
//if it completes before time out, it has no side effects
future.cancel(true);
}
public interface CustomCallable < T > extends Callable < T > {
void cancel();
RunnableFuture < T > newTask();
}
public class CustomExecutorPool extends ThreadPoolExecutor {
protected < T > RunnableFuture < T > newTaskFor(Callable < T > callable) {
if (callable instanceof CancellableTask)
return ((CancellableTask < T > ) callable).newTask();
else
return super.newTaskFor(callable);
}
}
public abstract class UnblockingIOTask < T > implements CustomCallable < T > {
public synchronized void cancel() {
try {
obj.close();
} catch (IOException e) {
logger.error("io exception", e);
}
}
public RunnableFuture < T > newTask() {
return new FutureTask < T > (this) {
public boolean cancel(boolean mayInterruptIfRunning) {
try {
this.cancel();
} finally {
return super.cancel(mayInterruptIfRunning);
}
}
};
}
}
I think that is easier than this.
You can change 'tabs' at left side of the wizard (General, Files, Options)
The other answerers are all correct, but a friend asked me to explain this to him and what it really boils down to is how Ruby handles variables, so I thought I would share some simple pictures / explanations I wrote for him (apologies for the length and probably some oversimplification):
str
to a value of 'foo'
?str = 'foo'
str.object_id # => 2000
str
is created that points at the object 'foo'
, which for the state of this Ruby interpreter happens to be at memory location 2000
.str
to a new object using =
?str = 'bar'.tap{|b| puts "bar: #{b.object_id}"} # bar: 2002
str.object_id # => 2002
str
now points to a different object.=
to str
?str2 = str
str2.object_id # => 2002
str2
is created that points at the same object as str
.str
and str2
gets changed?str2.replace 'baz'
str2 # => 'baz'
str # => 'baz'
str.object_id # => 2002
str2.object_id # => 2002
It's basically the same as what happens in Q3/Q4; the method gets its own private copy of the variable / label (str2
) that gets passed in to it (str
). It can't change which object the label str
points to, but it can change the contents of the object that they both reference to contain else:
str = 'foo'
def mutate(str2)
puts "str2: #{str2.object_id}"
str2.replace 'bar'
str2 = 'baz'
puts "str2: #{str2.object_id}"
end
str.object_id # => 2004
mutate(str) # str2: 2004, str2: 2006
str # => "bar"
str.object_id # => 2004
Using new String(byOriginal)
and converting back to byte[]
using getBytes()
doesn't guarantee two byte[]
with equal values. This is due to a call to StringCoding.encode(..)
which will encode the String
to Charset.defaultCharset()
. During this encoding, the encoder might choose to replace unknown characters and do other changes. Hence, using String.getBytes()
might not return an equal array as you've originally passed to the constructor.
The easiest way to do that is to use sets:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
set([5])
It means that element with id
passed to getElementById()
does not exist.
The other answers didn't work for me, but this did:
del /s /q *.svn
rmdir /s /q *.svn
/q disables Yes/No prompting
/s means delete the file(s) from all subdirectories.
There are a few more types than what's listed in the standard name list you've linked to. You can find more in the cryptographic providers documentation. The most common are certainly JKS
(the default) and PKCS12
(for PKCS#12 files, often with extension .p12
or sometimes .pfx
).
JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools (keytool
wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).
If you already have a PKCS#12 file, it's often easier to use the PKCS12
type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.
In Java 7, PKCS12
was mainly useful as a keystore but less for a truststore (see the difference between a keystore and a truststore), because you couldn't store certificate entries without a private key. In contrast, JKS
doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).
This has changed in Java 8, so you can now have certificate-only entries in PKCS12
stores too. (More details about these changes and further plans can be found in JEP 229: Create PKCS12 Keystores by Default.)
There are a few other keystore types, perhaps less frequently used (depending on the context), those include:
PKCS11
, for PKCS#11 libraries, typically for accessing hardware cryptographic tokens, but the Sun provider implementation also supports NSS stores (from Mozilla) through this.BKS
, using the BouncyCastle provider (commonly used for Android).Windows-MY
/Windows-ROOT
, if you want to access the Windows certificate store directly.KeychainStore
, if you want to use the OSX keychain directly.Javascript now has a specific built in object called Map, you can call as follows :
var myMap = new Map()
You can update it with .set :
myMap.set("key0","value")
This has the advantage of methods you can use to handle look ups, like the boolean .has
myMap.has("key1"); // evaluates to false
You can use this before calling .get on your Map object to handle looking up non-existent keys
std::copy is what you're looking for.
This can now be done in Chrome, Safari, Firefox 4+, and Internet Explorer 10pp4+!
See this question's answer for more information: Updating address bar with new URL without hash or reloading the page
Example:
function processAjaxData(response, urlPath){
document.getElementById("content").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
}
You can then use window.onpopstate
to detect the back/forward button navigation:
window.onpopstate = function(e){
if(e.state){
document.getElementById("content").innerHTML = e.state.html;
document.title = e.state.pageTitle;
}
};
For a more in-depth look at manipulating browser history, see this MDN article.
This is for future developers, you can also try this. Simple too
echo preg_replace('/\D/', '', '604-619-5135');
I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.
dangerouslySetInnerHtml
to embed the <video>
code. For example:<div dangerouslySetInnerHTML={{ __html: `
<video class="video-js" playsinline autoplay loop muted>
<source src="../video_path.mp4" type="video/mp4"/>
</video>`}}
/>
Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)
Simple solution that worked for me is, set the path of python in environment variables,it is done as follows
In the edit option click add and add following two paths to it one by one:
C:\Python27
C:\Python27\Scripts
and now close cmd and run it as administrator, by that pip will start working.
You can also use:
$container->getParameter('api_user');
Visit http://symfony.com/doc/current/service_container/parameters.html
Further to my comment against @JBall's answer that helped me along the way, this is the final answer that works for me. I'm using MVC and Razor and I'm submitting a form using jQuery AJAX so I can update a partial view with some new results and I didn't want to do a complete postback (and page flicker).
Add the @Html.AntiForgeryToken()
inside the form as usual.
My AJAX submission button code (i.e. an onclick event) is:
//User clicks the SUBMIT button
$("#btnSubmit").click(function (event) {
//prevent this button submitting the form as we will do that via AJAX
event.preventDefault();
//Validate the form first
if (!$('#searchForm').validate().form()) {
alert("Please correct the errors");
return false;
}
//Get the entire form's data - including the antiforgerytoken
var allFormData = $("#searchForm").serialize();
// The actual POST can now take place with a validated form
$.ajax({
type: "POST",
async: false,
url: "/Home/SearchAjax",
data: allFormData,
dataType: "html",
success: function (data) {
$('#gridView').html(data);
$('#TestGrid').jqGrid('setGridParam', { url: '@Url.Action("GetDetails", "Home", Model)', datatype: "json", page: 1 }).trigger('reloadGrid');
}
});
I've left the "success" action in as it shows how the partial view is being updated that contains an MvcJqGrid and how it's being refreshed (very powerful jqGrid grid and this is a brilliant MVC wrapper for it).
My controller method looks like this:
//Ajax SUBMIT method
[ValidateAntiForgeryToken]
public ActionResult SearchAjax(EstateOutlet_D model)
{
return View("_Grid", model);
}
I have to admit to not being a fan of POSTing an entire form's data as a Model but if you need to do it then this is one way that works. MVC just makes the data binding too easy so rather than subitting 16 individual values (or a weakly-typed FormCollection) this is OK, I guess. If you know better please let me know as I want to produce robust MVC C# code.
Had the same problem when Load external without cache using Javascript
Load external <script> without cache using Javascript
Had a good solution for cache problem here:
But this happend: Uncaught TypeError: Cannot read property 'appendChild' of null.
Here is good explanation: https://stackoverflow.com/a/58824439/14491024
As it said your script tag is in the head, the JavaScript is loaded before your HTML.
In Visual Studio by C# this problem is solved like this by adding Guid:
Here is how it looks in the View page source:
I think your EmpID
column is string and you forget to use ' '
in your value.
Because when you write EmpID=" + id.Text
, your command looks like EmpID = 12345
instead of EmpID = '12345'
Change your SqlCommand
to
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID='" + id.Text +"'", con);
Or as a better way you can (and should) always use parameterized queries
. This kind of string concatenations are open for SQL Injection
attacks.
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);
I think your EmpID
column keeps your employee id's, so it's type should some numerical type instead of character.
Built-in Helpers
#if
You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.
template
<div class="entry">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
{{else}}
<h1>Unknown Author</h1>
{{/if}}
</div>
When you pass the following input to the above template
{
author: true,
firstName: "Yehuda",
lastName: "Katz"
}
The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
That is all the language has to say, as far as C++03 is concerned.
You can also use .replaceWith()
, like this:
$("b").replaceWith(function() { return $(this).contents(); });
Or if you know it's just a string:
$("b").replaceWith(function() { return this.innerHTML; });
This can make a big difference if you're unwrapping a lot of elements since either approach above is significantly faster than the cost of .unwrap()
.
Here's a MySQL solution:
UPDATE mytable
SET number = (@n := COALESCE(number, @n))
ORDER BY date;
This is concise, but won't necessary work in other brands of RDBMS. For other brands, there might be a brand-specific solution that is more relevant. That's why it's important to tell us the brand you're using.
It's nice to be vendor-independent, as @Pax commented, but failing that, it's also nice to use your chosen brand of database to its fullest advantage.
Explanation of the above query:
@n
is a MySQL user variable. It starts out NULL, and is assigned a value on each row as the UPDATE runs through rows. Where number
is non-NULL, @n
is assigned the value of number
. Where number
is NULL, the COALESCE()
defaults to the previous value of @n
. In either case, this becomes the new value of the number
column and the UPDATE proceeds to the next row. The @n
variable retains its value from row to row, so subsequent rows get values that come from the prior row(s). The order of the UPDATE is predictable, because of MySQL's special use of ORDER BY with UPDATE (this is not standard SQL).
+1 way, that works in ksh, dash, etc: use printf to insert TAB:
grep "$(printf 'BEGIN\tEND')" testfile.txt
A quick definition of the "permanent generation":
"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]
In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space
if an application loads a large number of classes and/or on redeployment).
Note that PermSize
is additional to the -Xmx
value set by the user on the JVM options. But MaxPermSize
allows for the JVM to be able to grow the PermSize
to the amount specified. Initially when the VM is loaded, the MaxPermSize
will still be the default value (32mb for -client
and 64mb for -server
) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize
and MaxPermSize
to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx
setting.
If set is sufficient, ConcurrentSkipListSet might be used. (Its implementation is based on ConcurrentSkipListMap which implements a skip list.)
The expected average time cost is log(n) for the contains, add, and remove operations; the size method is not a constant-time operation.
All those ""
literals are the same object. Why make all that extra complexity? It's just longer to type and less clear (the cost to the compiler is minimal). Since Java's strings are immutable objects, there's never any need at all to distinguish between them except possibly as an efficiency thing, but with the empty string literal that's not a big deal.
If you really want an EmptyString
constant, make it yourself. But all it will do is encourage even more verbose code; there will never be any benefit to doing so.
HTML5 introduced a file upload api that allows you to monitor the progress of file uploads but for older browsers there's plupload a framework that specifically made to monitor file uploads and give information about them. plus it has plenty of callbacks so it can work across all browsers
Big thanks to Mike and Robertc for their helpful posts!
If you have two elements in your HTML and you want to :hover
over one and target a style change in the other the two elements must be directly related--parents, children or siblings. This means that the two elements either must be one inside the other or must both be contained within the same larger element.
I wanted to display definitions in a box on the right side of the browser as my users read through my site and :hover
over highlighted terms; therefore, I did not want the 'definition' element to be displayed inside the 'text' element.
I almost gave up and just added javascript to my page, but this is the future dang it! We should not have to put up with back sass from CSS and HTML telling us where we have to place our elements to achieve the effects we want! In the end we compromised.
While the actual HTML elements in the file must be either nested or contained in a single element to be valid :hover
targets to each other, the css position
attribute can be used to display any element where ever you want. I used position:fixed to place the target of my :hover
action where I wanted it on the user's screen regardless to its location in the HTML document.
The html:
<div id="explainBox" class="explainBox"> /*Common parent*/
<a class="defP" id="light" href="http://en.wikipedia.or/wiki/Light">Light /*highlighted term in text*/
</a> is as ubiquitous as it is mysterious. /*plain text*/
<div id="definitions"> /*Container for :hover-displayed definitions*/
<p class="def" id="light"> /*example definition entry*/ Light:
<br/>Short Answer: The type of energy you see
</p>
</div>
</div>
The css:
/*read: "when user hovers over #light somewhere inside #explainBox
set display to inline-block for #light directly inside of #definitions.*/
#explainBox #light:hover~#definitions>#light {
display: inline-block;
}
.def {
display: none;
}
#definitions {
background-color: black;
position: fixed;
/*position attribute*/
top: 5em;
/*position attribute*/
right: 2em;
/*position attribute*/
width: 20em;
height: 30em;
border: 1px solid orange;
border-radius: 12px;
padding: 10px;
}
In this example the target of a :hover
command from an element within #explainBox
must either be #explainBox
or also within #explainBox
. The position attributes assigned to #definitions force it to appear in the desired location (outside #explainBox
) even though it is technically located in an unwanted position within the HTML document.
I understand it is considered bad form to use the same #id
for more than one HTML element; however, in this case the instances of #light
can be described independently due to their respective positions in uniquely #id
'd elements. Is there any reason not to repeat the id
#light
in this case?
(This is based on @DarkXphenomenon's answer, which unfortunately had some problems.)
You need to enclose your code within this wrapper:
if _%1_==_payload_ goto :payload
:getadmin
echo %~nx0: elevating self
set vbs=%temp%\getadmin.vbs
echo Set UAC = CreateObject^("Shell.Application"^) >> "%vbs%"
echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
goto :eof
:payload
echo %~nx0: running payload with parameters:
echo %*
echo ---------------------------------------------------
cd /d %2
shift
shift
rem put your code here
rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
goto :eof
This makes batch file run itself as elevated user. It adds two parameters to the privileged code:
word payload
, to indicate this is payload call, i.e. already elevated. Otherwise
it would just open new processes over and over.
directory path where the main script was called. Due to the fact that Windows always starts elevated cmd.exe in "%windir%\system32", there's no easy way of knowing what the original path was (and retaining ability to copy your script around without touching code)
Note: Unfortunately, for some reason shift
does not work for %*
, so if you need
to pass actual arguments on, you will have to resort to the ugly notation I used
in the example (%1 %2 %3 %4 %5 %6 %7 %8 %9
), which also brings in the limit of
maximum of 9 arguments
I can't believe no-one has answered the ops question!
The last set of brackets are used for passing in the parameters to the anonymous function. So, the following example creates a function, then runs it with the x=5 and y=8
(function(x,y){
//code here
})(5,8)
This may seem not so useful, but it has its place. The most common one I have seen is
(function($){
//code here
})(jQuery)
which allows for jQuery to be in compatible mode, but you can refer to it as "$" within the anonymous function.
Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:
my $line = "file1.gz file1.gz file3.gz";
my @abc = split(/\s+/, $line);
This issue come when I am using PHP as server side language and the work around was to generate base64 enconding of my image before sending the result to client
$path = 'E:/pat/rwanda.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
I think may give someone idea to create his own work around
Thanks
The --force
option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.
If you tell rpm
to install all RPMs from some directory, then it does exactly this. rpm
will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.
You can remove the old RPM and rpm
will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.
If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm
to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i
(zypper in
can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.
I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles
. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify
command. It will complain for the new package if the old one has overwritten some files.
Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?
Correct answer is:
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var data = {};
$.each(items, function(itemNo, item) {
if (itemNo === 0) {
data.name = item;
} else {
data.y = parseFloat(item);
}
});
options.series[0].data.push(data);
data = {};
});
You need to flush the 'data' array.
data = {};
You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.
You can then import project to your workspace, copy paste project to your new workspace folder, then
File?Import?Existing project in to workspace?select project.
It look's like some permissions problem.
Try to set all permisions like you did in mysite1 to the others site.
By default file permissions should be 644 and dirs 755. Also check if the user that runs nginx have permission to read that files and dirs.
public class ConfigMan
{
#region Members
string _assemblyLocation;
Configuration _configuration;
#endregion Members
#region Constructors
/// <summary>
/// Loads config file settings for libraries that use assembly.dll.config files
/// </summary>
/// <param name="assemblyLocation">The full path or UNC location of the loaded file that contains the manifest.</param>
public ConfigMan(string assemblyLocation)
{
_assemblyLocation = assemblyLocation;
}
#endregion Constructors
#region Properties
Configuration Configuration
{
get
{
if (_configuration == null)
{
try
{
_configuration = ConfigurationManager.OpenExeConfiguration(_assemblyLocation);
}
catch (Exception exception)
{
}
}
return _configuration;
}
}
#endregion Properties
#region Methods
public string GetAppSetting(string key)
{
string result = string.Empty;
if (Configuration != null)
{
KeyValueConfigurationElement keyValueConfigurationElement = Configuration.AppSettings.Settings[key];
if (keyValueConfigurationElement != null)
{
string value = keyValueConfigurationElement.Value;
if (!string.IsNullOrEmpty(value)) result = value;
}
}
return result;
}
#endregion Methods
}
Just for something to do, I refactored the top answer into a class. The usage is something like:
ConfigMan configMan = new ConfigMan(this.GetType().Assembly.Location);
var setting = configMan.GetAppSetting("AppSettingsKey");
To give another approach.
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/service', methods=['POST'])
def service():
data = json.loads(request.data)
text = data.get("text",None)
if text is None:
return jsonify({"message":"text not found"})
else:
return jsonify(data)
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True)
$array = array( 'one' =>'value', 'two' => 'value2' );
$keys = array_keys($array);
echo $keys[0]; // one
echo $keys[1]; // two
Here is another seamless approach to convert JSON to Datatable using Cinchoo ETL - an open source library
Sample below shows how to convert
string json = @"[
{""id"":""10"",""name"":""User"",""add"":false,""edit"":true,""authorize"":true,""view"":true},
{ ""id"":""11"",""name"":""Group"",""add"":true,""edit"":false,""authorize"":false,""view"":true},
{ ""id"":""12"",""name"":""Permission"",""add"":true,""edit"":true,""authorize"":true,""view"":true}
]";
using (var r = ChoJSONReader.LoadText(json))
{
var dt = r.AsDataTable();
}
Hope it helps.
Try the SetField method:
By passing column object :
table.Rows[rowIndex].SetField(column, value);
By Passing column index :
table.Rows[rowIndex].SetField(0 /*column index*/, value);
By Passing column name as string :
table.Rows[rowIndex].SetField("product_name" /*columnName*/, value);
If you are using the date
package, this can be done fairly easily.
library(date)
Date <- c("01/01/2009", "01/01/2010", "01/01/2011", "01/01/2012")
Date <- as.date(Date)
Date
# [1] 1Jan2009 1Jan2010 1Jan2011 1Jan2012
date.mdy(Date)$year
# [1] 2009 2010 2011 2012
## be aware that these are now integers and thus different methods may be invoked:
str(date.mdy(Date)$year)
# int [1:4] 2009 2010 2011 2012
summary(Date)
# First Last
# "1Jan2009" "1Jan2012"
summary(date.mdy(Date)$year)
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 2009 2010 2010 2010 2011 2012
This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
@{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?
var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone',
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike
v7.6 release 92', 'Pike v7.8 release 517'];
// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
// Execute code
}
// If NOT on Apple device
else {
// Execute code
}
PROBLEM :-
Sometimes, Localhost may not get resolved. So it tends to return an output as seen below :
# curl -XGET localhost:9200/_cluster/health?pretty
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cluster/health?">http://localhost:9200/_cluster/health?</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>
<p>The system returned: <i>(111) Connection refused</i></p>
<p>The remote host or network may be down. Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A07%3A36%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cluster%2Fhealth%3Fpretty%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>
<br>
<hr>
<div id="footer">Generated Mon, 17 Dec 2018 08:07:36 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>
# curl -XGET localhost:9200/_cat/indices
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cat/indices">http://localhost:9200/_cat/indices</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>
<p>The system returned: <i>(111) Connection refused</i></p>
<p>The remote host or network may be down. Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A10%3A09%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cat%2Findices%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>
<br>
<hr>
<div id="footer">Generated Mon, 17 Dec 2018 08:10:09 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>
SOLUTION :-
Guess, this error is most probably returned by Local Squid deployed in the server.
So, it worked fine and good after replacing localhost by the local_ip in which the ElasticSearch has been deployed.
Expanding on Abdul's answer, you can obtain a KeyedTuple
instead of a discrete collection of rows by joining the columns:
q = Session.query(*User.__table__.columns + Document.__table__.columns).\
select_from(User).\
join(Document, User.email == Document.author).\
filter(User.email == 'someemail').all()
You can also try background:none;border:0px
to buttons.
also the css selectors are div#yes button{..}
and div#no button{..}
. hopes it helps
select @@version
Sample Output
Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Developer Edition (64-bit) on Windows NT 6.1 (Build 7600: )
If you just want to get the edition, you can use:
select serverproperty('Edition')
To use in an automated script, you can get the edition ID, which is an integer:
select serverproperty('EditionID')
Read: http://linuxmanpages.com/man1/sh.1.php & http://www.gnu.org/s/hello/manual/autoconf/Special-Shell-Variables.html
IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is ``''.
IFS is a shell environment variable so it will remain unchanged within the context of your Shell script but not otherwise, unless you EXPORT it. ALSO BE AWARE, that IFS will not likely be inherited from your Environment at all: see this gnu post for the reasons and more info on IFS.
You're code written like this:
IFS=","
for word in $(cat tmptest | sed -n 1'p' | tr ',' '\n'); do echo $word; done;
should work, I tested it on command line.
sh-3.2#IFS=","
sh-3.2#for word in $(cat tmptest | sed -n 1'p' | tr ',' '\n'); do echo $word; done;
World
Questions
Answers
bash shell
script
// This code works for images on 2.2, not sure if any other media types
//Your file path - Example here is "/sdcard/cats.jpg"
final String filePathThis = imagePaths.get(position).toString();
MediaScannerConnectionClient mediaScannerClient = new
MediaScannerConnectionClient() {
private MediaScannerConnection msc = null;
{
msc = new MediaScannerConnection(getApplicationContext(), this);
msc.connect();
}
public void onMediaScannerConnected(){
msc.scanFile(filePathThis, null);
}
public void onScanCompleted(String path, Uri uri) {
//This is where you get your content uri
Log.d(TAG, uri.toString());
msc.disconnect();
}
};
Jar class/package is for specific Jar file mechanisms where there is a manifest that is used by the Jar files in some cases.
The Zip file class/package handles any compressed files that include Jar files, which is a type of compressed file.
The Jar classes thus extend the Zip package classes.
because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:
SELECT *
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
Then note that we have two table aliases a
and b
. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b
, the statement will be:
UPDATE b
SET b.marks = a.marks
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a
only (leaving b intact) for those records that match by name:
DELETE a
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
You can use the SQL Fiddle created by JW as a playground
For me, when typing the url, a user accidentally used a / instead of a ? to start the query parameters
e.g.:
url.com/endpoint/parameter=SomeValue&otherparameter=Another+value
which should have been:
url.com/endpoint?parameter=SomeValue&otherparameter=Another+value
nchar and char pretty much operate in exactly the same way as each other, as do nvarchar and varchar. The only difference between them is that nchar/nvarchar store Unicode characters (essential if you require the use of extended character sets) whilst varchar does not.
Because Unicode characters require more storage, nchar/nvarchar fields take up twice as much space (so for example in earlier versions of SQL Server the maximum size of an nvarchar field is 4000).
This question is a duplicate of this one.
Use the placeholder attribute. The text disappears when the user starts typing. This is an example of a project I am working on:
<div class="" id="search-form">
<input type="text" name="" value="" class="form-control" placeholder="Search..." >
</div>
I believe this is what you're looking for:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);
From here.
System.AppDomain.CurrentDomain.FriendlyName
What you are asking is pretty straight forward
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
the following refernce should help
Getting Datafrom MySQL database
hope this helps :)
import { useRouter } from 'next/router';
function componentName() {
const router = useRouter();
console.log('router obj', router);
}
We can find the query object inside a router using which we can get all query string parameters.
In general, the index will be used if the assumed cost of using the index, and then possibly having to perform further bookmark lookups is lower than the cost of just scanning the entire table.
If your query is of the form:
SELECT Name from Table where Name = 'Boris'
And 1 row out of 1000 has the name Boris, it will almost certainly be used. If everyone's name is Boris, it will probably resort to a table scan, since the index is unlikely to be a more efficient strategy to access the data.
If it's a wide table (lot's of columns) and you do:
SELECT * from Table where Name = 'Boris'
Then it may still choose to perform the table scan, if it's a reasonable assumption that it's going to take more time retrieving the other columns from the table than it will to just look up the name, or again, if it's likely to be retrieving a lot of rows anyway.
This post will use Fibonacci numbers as a tool to build up to explaining the usefulness of Python generators.
This post will feature both C++ and Python code.
Fibonacci numbers are defined as the sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ....
Or in general:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2
This can be transferred into a C++ function extremely easily:
size_t Fib(size_t n)
{
//Fib(0) = 0
if(n == 0)
return 0;
//Fib(1) = 1
if(n == 1)
return 1;
//Fib(N) = Fib(N-2) + Fib(N-1)
return Fib(n-2) + Fib(n-1);
}
But if you want to print the first six Fibonacci numbers, you will be recalculating a lot of the values with the above function.
For example: Fib(3) = Fib(2) + Fib(1)
, but Fib(2)
also recalculates Fib(1)
. The higher the value you want to calculate, the worse off you will be.
So one may be tempted to rewrite the above by keeping track of the state in main
.
// Not supported for the first two elements of Fib
size_t GetNextFib(size_t &pp, size_t &p)
{
int result = pp + p;
pp = p;
p = result;
return result;
}
int main(int argc, char *argv[])
{
size_t pp = 0;
size_t p = 1;
std::cout << "0 " << "1 ";
for(size_t i = 0; i <= 4; ++i)
{
size_t fibI = GetNextFib(pp, p);
std::cout << fibI << " ";
}
return 0;
}
But this is very ugly, and it complicates our logic in main
. It would be better to not have to worry about state in our main
function.
We could return a vector
of values and use an iterator
to iterate over that set of values, but this requires a lot of memory all at once for a large number of return values.
So back to our old approach, what happens if we wanted to do something else besides print the numbers? We'd have to copy and paste the whole block of code in main
and change the output statements to whatever else we wanted to do.
And if you copy and paste code, then you should be shot. You don't want to get shot, do you?
To solve these problems, and to avoid getting shot, we may rewrite this block of code using a callback function. Every time a new Fibonacci number is encountered, we would call the callback function.
void GetFibNumbers(size_t max, void(*FoundNewFibCallback)(size_t))
{
if(max-- == 0) return;
FoundNewFibCallback(0);
if(max-- == 0) return;
FoundNewFibCallback(1);
size_t pp = 0;
size_t p = 1;
for(;;)
{
if(max-- == 0) return;
int result = pp + p;
pp = p;
p = result;
FoundNewFibCallback(result);
}
}
void foundNewFib(size_t fibI)
{
std::cout << fibI << " ";
}
int main(int argc, char *argv[])
{
GetFibNumbers(6, foundNewFib);
return 0;
}
This is clearly an improvement, your logic in main
is not as cluttered, and you can do anything you want with the Fibonacci numbers, simply define new callbacks.
But this is still not perfect. What if you wanted to only get the first two Fibonacci numbers, and then do something, then get some more, then do something else?
Well, we could go on like we have been, and we could start adding state again into main
, allowing GetFibNumbers to start from an arbitrary point.
But this will further bloat our code, and it already looks too big for a simple task like printing Fibonacci numbers.
We could implement a producer and consumer model via a couple of threads. But this complicates the code even more.
Instead let's talk about generators.
Python has a very nice language feature that solves problems like these called generators.
A generator allows you to execute a function, stop at an arbitrary point, and then continue again where you left off. Each time returning a value.
Consider the following code that uses a generator:
def fib():
pp, p = 0, 1
while 1:
yield pp
pp, p = p, pp+p
g = fib()
for i in range(6):
g.next()
Which gives us the results:
0 1 1 2 3 5
The yield
statement is used in conjuction with Python generators. It saves the state of the function and returns the yeilded value. The next time you call the next() function on the generator, it will continue where the yield left off.
This is by far more clean than the callback function code. We have cleaner code, smaller code, and not to mention much more functional code (Python allows arbitrarily large integers).
You better try with AsyncTask
Sample code -
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
public YourAsyncTask(MyMainActivity activity) {
dialog = new ProgressDialog(activity);
}
@Override
protected void onPreExecute() {
dialog.setMessage("Doing something, please wait.");
dialog.show();
}
@Override
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
@Override
protected void onPostExecute(Void result) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
Use the above code in your Login Button Activity. And, do the stuff in doInBackground
and onPostExecute
Update:
ProgressDialog
is integrated with AsyncTask
as you said your task takes time for processing.
Update:
ProgressDialog
class was deprecated as of API 26
Spaces in a folder name in your header search path can cause this problem. Make sure the folders in your project do not have spaces in their names.
Supplement to Mario Knezovic 's answer:
class IA
{
public:
virtual int getNum() const = 0;
};
class BaseA : public IA
{
public:
inline virtual int getNum() const final {return ...};
};
class ImplA : public BaseA {...};
IA* pa = ...;
...
ImplA* impla = static_cast<ImplA*>(pa);
//the following line should cause compiler to use the inlined function BaseA::getNum(),
//instead of dynamic binding (via vtable or something).
//any class/subclass of BaseA will benefit from it
int n = impla->getNum();
The above code shows the theory, but not actually tested on real compilers. Much appreciated if anyone paste a disassembled output.
<link rel="apple-touch-icon" sizes="114x114" href="${resource(dir: 'images', file:
'apple-touch-icon-retina.png')}">
or you can use this one
<link rel="shortcut icon" sizes="114x114" href="${resource(dir: 'images', file: 'favicon.ico')}"
type="image/x-icon">
After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
$(window).resize(function(){
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
map.fitBounds(group1.getBounds());
});
You can also destroy the old datatable
by using the following code before creating the new datatable
:
$("#example").dataTable().fnDestroy();
I use following solution:
1) Setup Jquery Validation Plugin
2) Then:
$('your form's selector').resetForm();
In swift
yourLabel.intrinsicContentSize().width
Often this question is asked in the context of Ron de Bruin's RangeToHTML
function, which creates an HTML PublishObject
from an Excel.Range
, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody
. In doing so, this removes the default signature (the RangeToHTML
function has a helper function GetBoiler
which attempts to insert the default signature).
Unfortunately, the poorly-documented Application.CommandBars
method is not available via Outlook:
wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"
It will raise a runtime 6158:
But we can still leverage the Word.Document
which is accessible via the MailItem.GetInspector
method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).
Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed
With OutMail
.To = "[email protected]"
.BCC = ""
.Subject = "Subject"
.Display
Dim wdDoc As Object '## Word.Document
Dim wdRange As Object '## Word.Range
Set wdDoc = OutMail.GetInspector.WordEditor
Set wdRange = wdDoc.Range(0, 0)
wdRange.InsertAfter vbCrLf & vbCrLf
'Copy the range in-place
rng.Copy
wdRange.Paste
End With
Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:
I'd say @Wim is right. You should use ToString()
for logfiles - assuming a technical audience - and Message
, if at all, to display to the user. One could argue that even that is not suitable for a user, for every exception type and occurance out there (think of ArgumentExceptions, etc.).
Also, in addition to the StackTrace, ToString()
will include information you will not get otherwise. For example the output of fusion, if enabled to include log messages in exception "messages".
Some exception types even include additional information (for example from custom properties) in ToString()
, but not in the Message.
Knowing the scope of each can make things easier to remember.
process
is node
's global object, and .cwd()
returns where node is running.
__dirname
is module
's property, and represents the file path of the module. In node, one module resides in one file.
Similarly, __filename
is another module
's property, which holds the file name of the module.
I made a bit more of a generic filter that I've used in multiple projects already:
HTML:
<input ng-model="customerNameFilter" />
<div ng-repeat="(key, value) in filter(customers, 'customerName', customerNameFilter" >
<p>Number: {{value.customerNo}}</p>
<p>Name: {{value.customerName}}</p>
</div>
JS:
$scope.filter = function(object, field, filter) {
if (!object) return {};
if (!filter) return object;
var filteredObject = {};
Object.keys(object).forEach(function(key) {
if (object[key][field] === filter) {
filteredObject[key] = object[key];
}
});
return filteredObject;
};
Here is the format of the Dockerfile:
We can use #
for commenting purpose#Comment
for example
#FROM microsoft/aspnetcore
FROM microsoft/dotnet
COPY /publish /app
WORKDIR /app
ENTRYPOINT ["dotnet", "WebApp.dll"]
From the above file when we build the docker, it skips the first line and goes to the next line because we have commented it using #
While what you want to accomplish may be useful, there is another option which I believe you might be overlooking that is much more simple.
You are correct, the Bootstrap tables act strangely when you have columns which are not fixed height. However, there is a bootstrap class created to combat this issue and perform responsive resets.
simply create an empty <div class="clearfix"></div>
before the start of each new row to allow the floats to reset and the columns to return to their correct positions.
here is a bootply.
This code gives you an error because your Add
function needs to be static
:
static public int Add(int x, int y)
In C# there is a distinction between functions that operate on instances (non-static) and functions that do not operate on instances (static). Instance functions can call other instance functions and static functions because they have an implicit reference to the instance. In contrast, static functions can call only static functions, or else they must explicitly provide an instance on which to call a non-static function.
Since public static void Main(string[] args)
is static, all functions that it calls need to be static as well.
+new
is equivalent to +alloc/-init
in Apple's NSObject
implementation. It is highly unlikely that this will ever change, but depending on your paranoia level, Apple's documentation for +new
appears to allow for a change of implementation (and breaking the equivalency) in the future. For this reason, because "explicit is better than implicit" and for historical continuity, the Objective-C community generally avoids +new
. You can, however, usually spot the recent Java comers to Objective-C by their dogged use of +new
.
I was running MAMP 4.1 on windows and MYSQL 5.7 .Was having this problem many times and found out a fix for this: For me deleting the log files was not working then just delete
and boom it starts working again. If this also doesn't work for your, remember to delete each file one by one and keep checking if any works for you. Make sure to backup always.
An addition to the solution by @Rafael Teles. The syntactic sugar Collectors.mapping
does the same in one step:
//...
List<Employee> employees = persons.stream()
.filter(p -> p.getLastName().equals("l1"))
.collect(
Collectors.mapping(
p -> new Employee(p.getName(), p.getLastName(), 1000),
Collectors.toList()));
Detailed example can be found here
This appears to be a very simple answer on how to differentiate between fact and dimension tables!
It may help to think of dimensions as things or objects. A thing such as a product can exist without ever being involved in a business event. A dimension is your noun. It is something that can exist independent of a business event, such as a sale. Products, employees, equipment, are all things that exist. A dimension either does something, or has something done to it.
Employees sell, customers buy. Employees and customers are examples of dimensions, they do.
Products are sold, they are also dimensions as they have something done to them.
Facts, are the verb. An entry in a fact table marks a discrete event that happens to something from the dimension table. A product sale would be recorded in a fact table. The event of the sale would be noted by what product was sold, which employee sold it, and which customer bought it. Product, Employee, and Customer are all dimensions that describe the event, the sale.
In addition fact tables also typically have some kind of quantitative data. The quantity sold, the price per item, total price, and so on.
Source: http://arcanecode.com/2007/07/23/dimensions-versus-facts-in-data-warehousing/
I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:
class Container extends React.Component {
constructor(props) {
super(props)
this.setRef = this.setRef.bind(this)
}
setRef(node) {
this.childRef = node
}
render() {
return <Child setRef={ this.setRef }/>
}
}
const Child = ({ setRef }) => (
<div ref={ setRef }>
</div>
)
Here's an example of doing this with a modal:
class Container extends React.Component {
constructor(props) {
super(props)
this.state = {
modalOpen: false
}
this.open = this.open.bind(this)
this.close = this.close.bind(this)
this.setModal = this.setModal.bind(this)
}
open() {
this.setState({ open: true })
}
close(event) {
if (!this.modal.contains(event.target)) {
this.setState({ open: false })
}
}
setModal(node) {
this.modal = node
}
render() {
let { modalOpen } = this.state
return (
<div>
<button onClick={ this.open }>Open</button>
{
modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
}
</div>
)
}
}
const Modal = ({ close, setModal }) => (
<div className='modal' onClick={ close }>
<div className='modal-window' ref={ setModal }>
</div>
</div>
)
In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).
Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396
Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396
In my case requests was already installed, but needed an upgrade. The following command did the trick
$ sudo pip install requests --upgrade
First, you may want to install glances:
sudo apt-get install python-pip build-essential python-dev lm-sensors
sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
sudo pip install glances
Then run it in the terminal!
glances
In your Python code, add at the begin of the file, the following:
import os
import gc # Garbage Collector
After using the "Big" variable (for example: myBigVar) for which, you would like to release memory, write in your python code the following:
del myBigVar
gc.collect()
In another terminal, run your python code and observe in the "glances" terminal, how the memory is managed in your system!
Good luck!
P.S. I assume you are working on a Debian or Ubuntu system
Markdown syntax for images (external/internal):
![test](https://github.com/favicon.ico)
HTML code for sizing images (internal/external):
<img src="https://github.com/favicon.ico" width="48">
Example:
This should work:
[[ http://url.to/image.png | height = 100px ]]
Source: https://guides.github.com/features/mastering-markdown/
If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:
@Produces({ "image/png", "image/jpg" })
@Provider
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage> {
@Override
public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
return type == BufferedImage.class;
}
@Override
public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
return -1; // not used in JAX-RS 2
}
@Override
public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
ImageIO.write(image, mt.getSubtype(), out);
}
}
This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.
Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:
@Path("/whatever")
@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
BufferedImage image = ...;
return Response.ok(image).build();
}
A couple of advantages to this approach:
If you have a _Layout.cshtml view like this
<html>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
then you can have an index.cshtml content view like this
@section scripts {
<script type="text/javascript">alert('hello');</script>
}
the required indicates whether or not the view using the layout page must have a scripts section
Thanks to CSS3
img
{
object-fit: contain;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
IE and EDGE as always outsiders: http://caniuse.com/#feat=object-fit
Try quoting the argument list:
Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"
You can also provide the argument list as an array (comma separated args) but using a string is usually easier.
Using only virtualenv (without virtualenvwrapper), setting environment variables is easy through the activate
script you sourcing in order to activate the virtualenv.
Run:
nano YOUR_ENV/bin/activate
Add the environment variables to the end of the file like this:
export KEY=VALUE
You can also set a similar hook to unset the environment variable as suggested by Danilo Bargen in his great answer above if you need.
If you want the variable inside the function available outside of the function, return the results of the variable inside the function.
var x = function returnX { var x = 0; return x; }
is the idea...
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
function makeObj(address) {
var trailimage = [address, 50, 50];
document.write('<img id="trailimageid" src="' + trailimage[0] + '" border="0" style=" position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px">');
obj_selected = 1;
return trailimage;
}
function truebody() {
return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
function hidetrail() {
var x = document.getElementById("trailimageid").style;
x.visibility = "hidden";
document.onmousemove = "";
}
function followmouse(e) {
var xcoord = offsetfrommouse[0];
var ycoord = offsetfrommouse[1];
var x = document.getElementById("trailimageid").style;
if (typeof e != "undefined") {
xcoord += e.pageX;
ycoord += e.pageY;
}
else if (typeof window.event != "undefined") {
xcoord += truebody().scrollLeft + event.clientX;
ycoord += truebody().scrollTop + event.clientY;
}
var docwidth = 1395;
var docheight = 676;
if (xcoord + trailimage[1] + 3 > docwidth || ycoord + trailimage[2] > docheight) {
x.display = "none";
alert("inja");
}
else
x.display = "";
x.left = xcoord + "px";
x.top = ycoord + "px";
}
if (obj_selected = 1) {
alert("obj_selected = true");
document.onmousemove = followmouse;
if (displayduration > 0)
setTimeout("hidetrail()", displayduration * 1000);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<img alt="" id="house" src="Pictures/sides/right.gif" style="z-index: 1; left: 372px; top: 219px; position: absolute; height: 138px; width: 120px" onclick="javascript:makeObj('Pictures/sides/sides-not-clicked.gif');" />
</form>
</body>
</html>
I haven't tested this, but if your code worked prior to that small change, then it should work.
Using br
elements is fine, and as long as you don't need a lot of space between elements, is actually a logical thing to do as anyone can read your code and understand what spacing logic you are using.
The alternative is to create a custom class for white space. In bootstrap 4 you can use
<div class="w-100"></div>
to make a blank row across the page, but this is no different to using the <br>
tag. The downside to creating a custom class for white space is that it can be a pain to read for others who view your code. A custom class would also apply the same amount of white space each time you used it, so if you wanted different amounts of white space on the same page, then you would need to create several white space classes.
In most cases, it is just easier to use <br>
or <div class="w-100"></div>
for the sake of ease and readability. it doesn't look pretty, but it works.
The OP implied that Java 7 was the need. And Java 6 is in fact no longer being 'supported' so 7 is the version you should be installing at this point unless you have legacy app concerns.
You can get it here: http://java.com/en/download/mac_download.jsp?locale=en
This is bad style, but I'll assume you have a good reason for doing something similar.
<html>
<body>
<input type="text" id="userInput">give me input</input>
<button id="submitter">Submit</button>
<div id="output"></div>
<script>
var didClickIt = false;
document.getElementById("submitter").addEventListener("click",function(){
// same as onclick, keeps the JS and HTML separate
didClickIt = true;
});
setInterval(function(){
// this is the closest you get to an infinite loop in JavaScript
if( didClickIt ) {
didClickIt = false;
// document.write causes silly problems, do this instead (or better yet, use a library like jQuery to do this stuff for you)
var o=document.getElementById("output"),v=document.getElementById("userInput").value;
if(o.textContent!==undefined){
o.textContent=v;
}else{
o.innerText=v;
}
}
},500);
</script>
</body>
</html>
You forgot the C: after the file:///
This works for me
<!DOCTYPE html>
<html>
<head>
<title>Experiment</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
html,body { width: 100%; height: 100%; }
</style>
</head>
<body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
</body>
</html>
Assuming all your macros are in modules, maybe this link will help. After copying the workbook, just iterate over each module and delete it
if i do os.environ["DEBUSSY"] = 1, it complains saying that 1 has to be string.
Then do
os.environ["DEBUSSY"] = "1"
I also want to know how to read the environment variables in python(in the later part of the script) once i set it.
Just use os.environ["DEBUSSY"]
, as in
some_value = os.environ["DEBUSSY"]
You can convert List<>
to Set<>
Set<T> set=new HashSet<T>();
//Added dependency -> If list is null then it will throw NullPointerExcetion.
Set<T> set;
if(list != null){
set = new HashSet<T>(list);
}
Arraylist narraylist=Arrays.asList(); // Returns immutable arraylist To make it mutable solution would be: Arraylist narraylist=new ArrayList(Arrays.asList());
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
Lot of good tips here, but inside Powershell I could not get it to work.
I am a .NET developer and we mainly still use Windows OS as we haven't made use of .Net core and cross platform so much, so my everyday use with Git is in a Windows environment, where the shell used is more often Powershell and not Git bash.
The following procedure can be followed to create an aliased function for adding untracked files in a Git repository.
Inside your $profile file of Powershell (in case it is missing - you can run: New-Item $Profile)
notepad $Profile
Now add this Powershell method:
function AddUntracked-Git() {
&git ls-files -o --exclude-standard | select | foreach { git add $_ }
}
Save the $profile file and reload it into Powershell. Then reload your $profile file with: . $profile
This is similar to the source command in *nix environments IMHO.
So next time you, if you are developer using Powershell in Windows against Git repo and want to just include untracked files you can run:
AddUntracked-Git
This follows the Powershell convention where you have verb-nouns.
You can use this code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
try {
File f = new File("src/com/data.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
System.out.println("Reading file using Buffered Reader");
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
sttr1.search(str2);
it will return the position of the match, or -1 if it isn't found.
In Linker, general, additional library directories, add the directory to the .dll or .libs you have included in Linker, Input. It does not work if you put this in VC++ Directories, Library Directories.
Please search "depends.exe" in google, it's a tiny utility to handle this.
Use a Comparator:
List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
@Override
public int compare(CustomObject left, CustomObject right) {
return left.getId() - right.getId(); // use your logic
}
};
Collections.sort(list, comparator); // use the comparator as much as u want
System.out.println(list);
Additionally, if CustomObject
implements Comparable
, then just use Collections.sort(list)
List<CustomObject> list = getCustomObjectList();
Collections.sort(list, (left, right) -> left.getId() - right.getId());
System.out.println(list);
Much simplier
List<CustomObject> list = getCustomObjectList();
list.sort((left, right) -> left.getId() - right.getId());
System.out.println(list);
Simplest
List<CustomObject> list = getCustomObjectList();
list.sort(Comparator.comparing(CustomObject::getId));
System.out.println(list);
Obviously the initial code can be used for JDK 8 too.
Is the maximum recommended title length really 50?
I have believed this for years, but as I just noticed the documentation of "git commit" actually states
$ git help commit | grep -C 1 50
Though not required, it’s a good idea to begin the commit message with
a single short (less than 50 character) line summarizing the change,
followed by a blank line and then a more thorough description. The text
$ git version
git version 2.11.0
One could argue that "less then 50" can only mean "no longer than 49".
DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clauseIn a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
DISTINCT
to find unique aggregate function valuesIn a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
DISTINCT
to remove duplicates with more than one GROUP BY
columnAnother case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
I have heard an explanation, that is:" NP-Completeness is probably one of the more enigmatic ideas in the study of algorithms. "NP" stands for "nondeterministic polynomial time," and is the name for what is called a complexity class to which problems can belong. The important thing about the NP complexity class is that problems within that class can be verified by a polynomial time algorithm. As an example, consider the problem of counting stuff. Suppose there are a bunch of apples on a table. The problem is "How many apples are there?" You are provided with a possible answer, 8. You can verify this answer in polynomial time by using the algorithm of, duh, counting the apples. Counting the apples happens in O(n) (that's Big-oh notation) time, because it takes one step to count each apple. For n apples, you need n steps. This problem is in the NP complexity class.
A problem is classified as NP-complete if it can be shown that it is both NP-Hard and verifiable in polynomial time. Without going too deeply into the discussion of NP-Hard, suffice it to say that there are certain problems to which polynomial time solutions have not been found. That is, it takes something like n! (n factorial) steps to solve them. However, if you're given a solution to an NP-Complete problem, you can verify it in polynomial time.
A classic example of an NP-Complete problem is The Traveling Salesman Problem."
The author: ApoxyButt From: http://www.everything2.com/title/NP-complete
There are two problems in your code:
visibility
and not visiblity
..style
property.It's easy to fix. Simple replace this:
document.getElementById("remember").visiblity
with this:
document.getElementById("remember").style.visibility
Just modify one of the returned entities:
Customer c = (from x in dataBase.Customers
where x.Name == "Test"
select x).First();
c.Name = "New Name";
dataBase.SaveChanges();
Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}
$result = If ($condition) {"true"} Else {"false"}
Everything else is incidental complexity and thus to be avoided.
For use in or as an expression, not just an assignment, wrap it in $()
, thus:
write-host $(If ($condition) {"true"} Else {"false"})
In the header file
header file
#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef MAIN_FILE
int global;
#else
extern int global;
#endif
#endif
In the file with the file you want the global to live:
#define MAIN_FILE
#include "share.h"
In the other files that need the extern version:
#include "share.h"
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;
The best solution for your problem is to utilize a Pool
. Using Queue
s and having a separate "queue feeding" functionality is probably overkill.
Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool
. I believe it's the easiest way to go, with minimal changes to original code:
import multiprocessing
import time
data = (
['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)
def mp_worker((inputs, the_time)):
print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
time.sleep(int(the_time))
print " Process %s\tDONE" % inputs
def mp_handler():
p = multiprocessing.Pool(2)
p.map(mp_worker, data)
if __name__ == '__main__':
mp_handler()
Note that mp_worker()
function now accepts a single argument (a tuple of the two previous arguments) because the map()
function chunks up your input data into sublists, each sublist given as a single argument to your worker function.
Output:
Processs a Waiting 2 seconds
Processs b Waiting 4 seconds
Process a DONE
Processs c Waiting 6 seconds
Process b DONE
Processs d Waiting 8 seconds
Process c DONE
Processs e Waiting 1 seconds
Process e DONE
Processs f Waiting 3 seconds
Process d DONE
Processs g Waiting 5 seconds
Process f DONE
Processs h Waiting 7 seconds
Process g DONE
Process h DONE
Edit as per @Thales comment below:
If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:
A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...
then change the handler function to launch pools (of 2 processes) for each pair of data:
def mp_handler():
subdata = zip(data[0::2], data[1::2])
for task1, task2 in subdata:
p = multiprocessing.Pool(2)
p.map(mp_worker, (task1, task2))
Now your output is:
Processs a Waiting 2 seconds
Processs b Waiting 4 seconds
Process a DONE
Process b DONE
Processs c Waiting 6 seconds
Processs d Waiting 8 seconds
Process c DONE
Process d DONE
Processs e Waiting 1 seconds
Processs f Waiting 3 seconds
Process e DONE
Process f DONE
Processs g Waiting 5 seconds
Processs h Waiting 7 seconds
Process g DONE
Process h DONE
print_elapsed_time function is below
def print_elapsed_time(prefix=''):
e_time = time.time()
if not hasattr(print_elapsed_time, 's_time'):
print_elapsed_time.s_time = e_time
else:
print(f'{prefix} elapsed time: {e_time - print_elapsed_time.s_time:.2f} sec')
print_elapsed_time.s_time = e_time
use it in this way
print_elapsed_time()
.... heavy jobs ...
print_elapsed_time('after heavy jobs')
.... tons of jobs ...
print_elapsed_time('after tons of jobs')
result is
after heavy jobs elapsed time: 0.39 sec
after tons of jobs elapsed time: 0.60 sec
the pros and cons of this function is that you don't need to pass start time
First and foremost, a RESTful web service is STATELESS (or in other words, SESSIONLESS). Therefore, a RESTful service does not have and should not have a concept of session or cookies involved. The way to do authentication or authorization in the RESTful service is by using the HTTP Authorization header as defined in the RFC 2616 HTTP specifications. Every single request should contain the HTTP Authorization header, and the request should be sent over an HTTPs (SSL) connection. This is the correct way to do authentication and to verify the authorization of requests in a HTTP RESTful web services. I have implemented a RESTful web service for the Cisco PRIME Performance Manager application at Cisco Systems. And as part of that web service, I have implemented authentication/authorization as well.
Use $ne
-- $not
should be followed by the standard operator:
An examples for $ne
, which stands for not equal:
use test
switched to db test
db.test.insert({author : 'me', post: ""})
db.test.insert({author : 'you', post: "how to query"})
db.test.find({'post': {$ne : ""}})
{ "_id" : ObjectId("4f68b1a7768972d396fe2268"), "author" : "you", "post" : "how to query" }
And now $not
, which takes in predicate ($ne
) and negates it ($not
):
db.test.find({'post': {$not: {$ne : ""}}})
{ "_id" : ObjectId("4f68b19c768972d396fe2267"), "author" : "me", "post" : "" }
This might help //Printing The Array
for (int i = 0; i < n; i++)
{cout << numbers[i];}
n is the size of the array
You would need to manage the referential constraint across databases using a Trigger.
Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception.
Example:
Create Trigger dbo.MyTableTrigger ON dbo.MyTable, After Insert, Update
As
Begin
If NOT Exists(select PK from OtherDB.dbo.TableName where PK in (Select FK from inserted) BEGIN
-- Handle the Referential Error Here
END
END
Edited: Just to clarify. This is not the best approach with enforcing referential integrity. Ideally you would want both tables in the same db but if that is not possible. Then the above is a potential work around for you.
git add
selects changes
git commit
records changes LOCALLY
git push
shares changes
based from the answer of @SW4, you could also add a little animation at the end.
body > div{_x000D_
border:1px solid grey;_x000D_
}_x000D_
html, body, #container {_x000D_
height:100%;_x000D_
width:100%;_x000D_
margin:0;_x000D_
padding:0;_x000D_
}_x000D_
#container {_x000D_
overflow:hidden;_x000D_
position:relative;_x000D_
}_x000D_
#hideMe {_x000D_
-webkit-animation: cssAnimation 5s forwards; _x000D_
animation: cssAnimation 5s forwards;_x000D_
}_x000D_
@keyframes cssAnimation {_x000D_
0% {opacity: 1;}_x000D_
90% {opacity: 1;}_x000D_
100% {opacity: 0;}_x000D_
}_x000D_
@-webkit-keyframes cssAnimation {_x000D_
0% {opacity: 1;}_x000D_
90% {opacity: 1;}_x000D_
100% {opacity: 0;}_x000D_
}
_x000D_
<div>_x000D_
<div id='container'>_x000D_
<div id='hideMe'>Wait for it...</div>_x000D_
</div>_x000D_
</div>
_x000D_
Making the remaining 0.5 seconds to animate the opacity attribute. Just make sure to do the math if you're changing the length, in this case, 90% of 5 seconds leaves us 0.5 seconds to animate the opacity.