Extend is used when a use case adds steps to another first-class use case.
For example, imagine "Withdraw Cash" is a use case of an Automated Teller Machine (ATM). "Assess Fee" would extend Withdraw Cash and describe the conditional "extension point" that is instantiated when the ATM user doesn't bank at the ATM's owning institution. Notice that the basic "Withdraw Cash" use case stands on its own, without the extension.
Include is used to extract use case fragments that are duplicated in multiple use cases. The included use case cannot stand alone and the original use case is not complete without the included one. This should be used sparingly and only in cases where the duplication is significant and exists by design (rather than by coincidence).
For example, the flow of events that occurs at the beginning of every ATM use case (when the user puts in their ATM card, enters their PIN, and is shown the main menu) would be a good candidate for an include.
If for a some reason can't use rsyslog, this will do:
ExecStart=/bin/bash -ce "exec /usr/local/bin/binary1 agent -config-dir /etc/sample.d/server >> /var/log/agent.log 2>&1"
As Yaron mentioned, there isn't any difference between where
and filter
.
filter
is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.
We can use explain()
to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name
and person_country
columns. All of the following code snippets will return the same Physical Plan below:
df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()
These all return this Physical Plan:
== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
+- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>
The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.
Android follows the same naming conventions like Java,
Naming Conventions
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).
Packages in the Java language itself begin with java. or javax.
In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:
Legalizing Package Names:
Domain Name Package Name Prefix
hyphenated-name.example.org org.example.hyphenated_name
example.int int_.example
123name.example.com com.example._123name
Put this code wherever you want to insert a new line:
bufferedWriter.newLine();
For the above issue, first of all if suppose tables contains more than 1 primary key then first remove all those primary keys and add first AUTO INCREMENT field as primary key then add another required primary keys which is removed earlier. Set AUTO INCREMENT option for required field from the option area.
There is no other way - except implementing lazy loading.
Or manual loading....
myobj = context.MyObjects.First();
myobj.ChildA.Load();
myobj.ChildB.Load();
...
First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).
Second, the -vm argument in eclipse.ini
should point to the java executable. See
http://wiki.eclipse.org/Eclipse.ini for examples.
If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?
Something like this will do it. The for
loop may need to be modified depending on which filenames you wish to capture.
for fspec1 in DET01-ABC-5_50-*.dat ; do
fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
mv ${fspec1} ${fspec2}
done
You should always test these scripts on copies of your data, by the way, and in totally different directories.
I know this is old and there are several good solutions already posted, but a simple solution that worked for me is the following CSS
<style>
.divider{
margin: 0cm 0cm .5cm 0cm;
}
</style>
and then create a div in your html
<div class="divider"></div>
You can even try this.
String date="09/08/1980"; // take a string date
Timestamp ts=null; //declare timestamp
Date d=new Date(date); // Intialize date with the string date
if(d!=null){ // simple null check
ts=new java.sql.Timestamp(d.getTime()); // convert gettime from date and assign it to your timestamp.
}
Just use Date.parse()
which returns a Number, then use new Date()
to parse it:
var thedate = new Date(Date.parse("2011-07-14 11:23:00"));
If you want to center one element itself you could use alignSelf:
logoImg: {
position: 'absolute',
alignSelf: 'center',
bottom: '-5%'
}
This is an example (Note the logo parent is a view with position: relative)
'SET' is forgotten
ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';
I don't have enough reputation points to comment on the recommendation to use *.csv >> ConcatenatedFile.csv
, but I can add a warning:
If you create ConcatenatedFile.csv
file in the same directory that you are using for concatenation it will be added to itself.
In Firefox the onchange fires only when you tab or else click outside the input field. The same is true of Onblur. The difference is that onblur will fire whether you changed anything in the field or not. It is possible that ENTER will fire one or both of these, but you wouldn't know that if you disable the ENTER in your forms to prevent unexpected submits.
(From http://git.or.cz/gitwiki/GitTips#head-9f87cd21bcdf081a61c29985604ff4be35a5e6c0)
How to change commits deeper in history
Since history in Git is immutable, fixing anything but the most recent commit (commit which is not branch head) requires that the history is rewritten from the changed commit and forward.
You can use StGIT for that, initialize branch if necessary, uncommitting up to the commit you want to change, pop to it if necessary, make a change then refresh patch (with -e option if you want to correct commit message), then push everything and stg commit.
Or you can use rebase to do that. Create new temporary branch, rewind it to the commit you want to change using git reset --hard, change that commit (it would be top of current head), then rebase branch on top of changed commit, using git rebase --onto .
Or you can use git rebase --interactive, which allows various modifications like patch re-ordering, collapsing, ...
I think that should answer your question. However, note that if you have pushed code to a remote repository and people have pulled from it, then this is going to mess up their code histories, as well as the work they've done. So do it carefully.
I think a good way to solve this problem is to use a custom interface.
Lets say you have two fragments (A and B) which are inside of the same activity and you want to send data from A to B.
Interface :
public interface OnDataSentListener{
void onDataSent(Object data);
}
Activity:
public class MyActivity extends AppCompatActivity{
private OnDataSentListener onDataSentListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
FragmentTransaction trans = getFragmentManager().beginTransaction();
FragmentA fa = new FragmentA();
FragmentB fb = new FragmentB();
fa.setOnDataSentListener(new Listeners.OnDataSentListener() {
@Override
public void onDataSent(Object data) {
if(onDataSentListener != null) onDataSentListener.onDataSent(data);
}
});
transaction.add(R.id.frame_a, fa);
transaction.add(R.id.frame_b, fb);
transaction.commit();
}
public void setOnDataSentListener(OnDataSentListener listener){
this.onDataSentListener = listener;
}
}
Fragment A:
public class FragmentA extends Fragment{
private OnDataSentListener onDataSentListener;
private void sendDataToFragmentB(Object data){
if(onDataSentListener != null) onDataSentListener.onDataSent(data);
}
public void setOnDataSentListener(OnDataSentListener listener){
this.onDataSentListener = listener;
}
}
Fragment B:
public class FragmentB extends Fragment{
private void initReceiver(){
((MyActivity) getActivity()).setOnDataSentListener(new OnDataSentListener() {
@Override
public void onDataSent(Object data) {
//Here you receive the data from fragment A
}
});
}
}
if you just want the number of occurences then you can do this, $ grep -c "string_to_count" file_name
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
Solve NSURLConnection Http load failed bug Just Add following Dict in info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
</dict>
Assuming my-app is a subdirectory under the current directory. The $LASTEXITCODE should be there from the last command:
.\my-app\my-fle.bat
If it was from a fileshare:
\\server\my-file.bat
To remove a scrollbar from a view (and its subclass) via xml:
android:scrollbars="none"
http://developer.android.com/reference/android/view/View.html#attr_android:scrollbars
I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B
I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.
The above occurs when you use a modal inside another modal. When I open a modal inside another modal, the closing of the latter removes the class modal-open
from the body
. The fix of the issue depends on how you close the latter modal.
If you close the modal with html like,
<button type="button" class="btn" data-dismiss="modal">Close</button>
Then you have to add a listener like this,
$(modalSelector).on("hidden.bs.modal", function (event) {
event.stopPropagation();
$("body").addClass("modal-open");
return false;
});
If you close the modal using javascript like,
$(modalSelector).modal("hide");
Then you have to run the command some time after like this,
setInterval(function(){$("body").addClass("modal-open");}, 300);
PHP uses weak typing (which it calls 'type juggling'), which is a bad idea (though that's a conversation for another time). When you try to use a variable in a context that requires a boolean, it will convert whatever your variable is into a boolean, according to some mostly arbitrary rules available here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
Another way to do something similar is with flexbox on a wrapper element, i.e.,
.row {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}
_x000D_
<div class="row">_x000D_
<div>Left</div>_x000D_
<div>Right</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
Not smarter but simpler:
select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%';
This is tested and easy to understand.
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x84:
base.WndProc(ref m);
if((int)m.Result == 0x1)
m.Result = (IntPtr)0x2;
return;
}
base.WndProc(ref m);
}
You can use insertRule if you don't need to support IE < 9, according to dottoro. There's a bit of cross browser code over there as well.
document.styleSheets[0].insertRule('#my-window {\
position: fixed;\
z-index: 102;\
display:none;\
top:50%;\
left:50%;\
}', 0)
apt-get install python-dev
...solved the problem for me.
On Linux, use the service of "Network Manager" over the DBus.
There is also good'ol shell program which can be invoke and the result grabbed (use an exec function under C):
$ /sbin/ifconfig | grep HWaddr
for whole row
insert into xyz select * from xyz2 where id="1";
for selected column
insert into xyz(t_id,v_id,f_name) select t_id,v_id,f_name from xyz2 where id="1";
jQuery has very helpful function called serialize.
Demo: http://jsfiddle.net/55xnJ/2/
//Just type:
$("#preview_form").serialize();
//to get result:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
Hopefully this is the simplest way
string Commaseplist;
string[] itemList = { "Test1", "Test2", "Test3" };
Commaseplist = string.join(",",itemList);
Console.WriteLine(Commaseplist); //Outputs Test1,Test2,Test3
krosenvold's answer inspired the following script which does the following:
the script is restartable and checks the existence of the intermediate files. It also uses pv and qemu-img -p to show the progress of each step.
In my environment 2 x Ubuntu 12.04 LTS the steps took:
#!/bin/bash
# get a dd disk dump and convert it to vmware
# see http://stackoverflow.com/questions/454899/how-to-convert-flat-raw-disk-image-to-vmdk-for-virtualbox-or-vmplayer
# Author: wf 2014-10-1919
#
# get a dd dump from the given host's given disk and create a compressed
# image at the given target
#
# 1: host e.g. somehost.somedomain
# 2: disk e.g. sda
# 3: target e.g. image.gz
#
# http://unix.stackexchange.com/questions/132797/how-to-use-ssh-to-make-a-dd-copy-of-disk-a-from-host-b-and-save-on-disk-b
getdump() {
local l_host="$1"
local l_disk="$2"
local l_target="$3"
echo "getting disk dump of $l_disk from $l_host"
ssh $l_host sudo fdisk -l | egrep "^/dev/$l_disk"
if [ $? -ne 0 ]
then
echo "device $l_disk does not exist on host $l_host" 1>&2
exit 1
else
if [ ! -f $l_target ]
then
ssh $l_host "sudo dd if=/dev/$disk bs=1M | gzip -1 -" | pv | dd of=$l_target
else
echo "$l_target already exists"
fi
fi
}
#
# optionally install command from package if it is not available yet
# 1: command
# 2: package
#
opt_install() {
l_command="$1"
l_package="$2"
echo "checking that $l_command from package $l_package is installed ..."
which $l_command
if [ $? -ne 0 ]
then
echo "installing $l_package to make $l_command available ..."
sudo apt-get install $l_package
fi
}
#
# convert the given image to vmware
# 1: the dd dump image
# 2: the vmware image file to convert to
#
vmware_convert() {
local l_ddimage="$1"
local l_vmwareimage="$2"
echo "converting dd image $l_image to vmware $l_vmwareimage"
# convert to VMware disk format showing progess
# see http://manpages.ubuntu.com/manpages/precise/man1/qemu-img.1.html
qemu-img convert -p -O vmdk "$l_ddimage" "$l_vmwareimage"
}
#
# show usage
#
usage() {
echo "usage: $0 host device"
echo " host: the host to get the disk dump from e.g. frodo.lotr.org"
echo " you need ssh and sudo privileges on that host"
echo "
echo " device: the disk to dump from e.g. sda"
echo ""
echo " examples:
echo " $0 frodo.lotr.org sda"
echo " $0 gandalf.lotr.org sdb"
echo ""
echo " the needed packages pv and qemu-utils will be installed if not available"
echo " you need local sudo rights for this to work"
exit 1
}
# check arguments
if [ $# -lt 2 ]
then
usage
fi
# get the command line parameters
host="$1"
disk="$2"
# calculate the names of the image files
ts=`date "+%Y-%m-%d"`
# prefix of all images
# .gz the zipped dd
# .dd the disk dump file
# .vmware - the vmware disk file
image="${host}_${disk}_image_$ts"
echo "$0 $host/$disk -> $image"
# first check/install necessary packages
opt_install qemu-img qemu-utils
opt_install pv pv
# check if dd files was already loaded
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.gz ]
then
getdump $host $disk $image.gz
else
echo "$image.gz already downloaded"
fi
# check if the dd file was already uncompressed
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.dd ]
then
echo "uncompressing $image.gz"
zcat $image.gz | pv -cN zcat > $image.dd
else
echo "image $image.dd already uncompressed"
fi
# check if the vmdk file was already converted
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.vmdk ]
then
vmware_convert $image.dd $image.vmdk
else
echo "vmware image $image.vmdk already converted"
fi
I have the same error as this topic when I restore a new database using an old database. (using .bak gives the same error)
I Changed the name of old database by name of new database (same this picture). It worked.
I think you just need to make
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
Before calling your .js files or code
This seems to solve the problem, using the [index: TYPE]
array access type, cheers.
interface ScriptNodeList extends NodeList {
[index: number]: HTMLScriptElement;
}
var script = ( <ScriptNodeList>document.getElementsByName('foo') )[0];
Inversion of control is a pattern used for decoupling components and layers in the system. The pattern is implemented through injecting dependencies into a component when it is constructed. These dependences are usually provided as interfaces for further decoupling and to support testability. IoC / DI containers such as Castle Windsor, Unity are tools (libraries) which can be used for providing IoC. These tools provide extended features above and beyond simple dependency management, including lifetime, AOP / Interception, policy, etc.
a. Alleviates a component from being responsible for managing it's dependencies.
b. Provides the ability to swap dependency implementations in different environments.
c. Allows a component be tested through mocking of dependencies.
d. Provides a mechanism for sharing resources throughout an application.
a. Critical when doing test-driven development. Without IoC it can be difficult to test, because the components under test are highly coupled to the rest of the system.
b. Critical when developing modular systems. A modular system is a system whose components can be replaced without requiring recompilation.
c. Critical if there are many cross-cutting concerns which need to addressed, partilarly in an enterprise application.
This FutureWarning isn't from Pandas, it is from numpy and the bug also affects matplotlib and others, here's how to reproduce the warning nearer to the source of the trouble:
import numpy as np
print(np.__version__) # Numpy version '1.12.0'
'x' in np.arange(5) #Future warning thrown here
FutureWarning: elementwise comparison failed; returning scalar instead, but in the
future will perform elementwise comparison
False
Another way to reproduce this bug using the double equals operator:
import numpy as np
np.arange(5) == np.arange(5).astype(str) #FutureWarning thrown here
An example of Matplotlib affected by this FutureWarning under their quiver plot implementation: https://matplotlib.org/examples/pylab_examples/quiver_demo.html
There is a disagreement between Numpy and native python on what should happen when you compare a strings to numpy's numeric types. Notice the left operand is python's turf, a primitive string, and the middle operation is python's turf, but the right operand is numpy's turf. Should you return a Python style Scalar or a Numpy style ndarray of Boolean? Numpy says ndarray of bool, Pythonic developers disagree. Classic standoff.
Should it be elementwise comparison or Scalar if item exists in the array?
If your code or library is using the in
or ==
operators to compare python string to numpy ndarrays, they aren't compatible, so when if you try it, it returns a scalar, but only for now. The Warning indicates that in the future this behavior might change so your code pukes all over the carpet if python/numpy decide to do adopt Numpy style.
Numpy and Python are in a standoff, for now the operation returns a scalar, but in the future it may change.
https://github.com/numpy/numpy/issues/6784
https://github.com/pandas-dev/pandas/issues/7830
Either lockdown your version of python and numpy, ignore the warnings and expect the behavior to not change, or convert both left and right operands of ==
and in
to be from a numpy type or primitive python numeric type.
Suppress the warning globally:
import warnings
import numpy as np
warnings.simplefilter(action='ignore', category=FutureWarning)
print('x' in np.arange(5)) #returns False, without Warning
Suppress the warning on a line by line basis.
import warnings
import numpy as np
with warnings.catch_warnings():
warnings.simplefilter(action='ignore', category=FutureWarning)
print('x' in np.arange(2)) #returns False, warning is suppressed
print('x' in np.arange(10)) #returns False, Throws FutureWarning
Just suppress the warning by name, then put a loud comment next to it mentioning the current version of python and numpy, saying this code is brittle and requires these versions and put a link to here. Kick the can down the road.
TLDR: pandas
are Jedi; numpy
are the hutts; and python
is the galactic empire. https://youtu.be/OZczsiCfQQk?t=3
If you want it visually formatted to two decimals as a string (for output) use toFixed()
:
var priceString = someValue.toFixed(2);
The answer by @David has two problems:
It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999
instead of "134.20"
.
If your value is an integer or rounds to one tenth, you will not see the additional decimal value:
var n = 1.099;
(Math.round( n * 100 )/100 ).toString() //-> "1.1"
n.toFixed(2) //-> "1.10"
var n = 3;
(Math.round( n * 100 )/100 ).toString() //-> "3"
n.toFixed(2) //-> "3.00"
And, as you can see above, using toFixed()
is also far easier to type. ;)
date_default_timezone_set('Australia/Melbourne');
$time = date("Y-m-d H:i:s", time());
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
A nice Java 7+ answer from Benoit Blanchon can be found here:
With Java 7, you can use
Files.createDirectories()
.For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
No, you have to use javascript once it's in the DOM or format it via your language server-side (PHP/ruby/python etc.)
Do checks like that in a controller function. Your HTML should be easy-to-read markup without logic.
Controller:
angular.module("myApp")
.controller("myController",function(){
var self = this;
self.select = { /* ... */ };
self.showFoo = function() {
//Checks if self.select.name contains the character '?'
return self.select.name.indexOf('?') != -1;
}
});
Page example:
<div ng-app="myApp" ng-controller="myController as vm">
<p ng-show="vm.showFoo()">Bar</p>
</div>
I am trying to push value in an array state and set value like this and define state array and push value by map function.
this.state = {
createJob: [],
totalAmount:Number=0
}
your_API_JSON_Array.map((_) => {
this.setState({totalAmount:this.state.totalAmount += _.your_API_JSON.price})
this.state.createJob.push({ id: _._id, price: _.your_API_JSON.price })
return this.setState({createJob: this.state.createJob})
})
Like the previous comment mention, the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." its a warning because you are missunderstanding this line: mongoose.connect('mongodb://localhost/info'); and browsing this url: http://localhost:28017/
However, if you want to see the mongo's admin web page, you could do it, with this command:
mongod --rest --httpinterface
browsing this url: http://localhost:28017/
the parameter httpinterface activate the admin web page, and the parameter rest its needed for activate the rest services the page require
For python version >= 3.6 (see PEP 498)
s1='albha'
s2='beta'
f'{s1}{s2:>10}'
#output
'albha beta'
Delegates always confused me until I realized that a delegate is just a class that does some work for another class. It's like having someone else there to do all the dirty work for you that you don't want to do yourself.
I wrote a little story to illustrate this. Read it in a Playground if you like.
// MARK: Background to the story
// A protocol is like a list of rules that need to be followed.
protocol OlderSiblingDelegate: class {
// The following command (ie, method) must be obeyed by any
// underling (ie, delegate) of the older sibling.
func getYourNiceOlderSiblingAGlassOfWater()
}
// MARK: Characters in the story
class BossyBigBrother {
// I can make whichever little sibling is around at
// the time be my delegate (ie, slave)
weak var delegate: OlderSiblingDelegate?
func tellSomebodyToGetMeSomeWater() {
// The delegate is optional because even though
// I'm thirsty, there might not be anyone nearby
// that I can boss around.
delegate?.getYourNiceOlderSiblingAGlassOfWater()
}
}
// Poor little sisters have to follow (or at least acknowledge)
// their older sibling's rules (ie, protocol)
class PoorLittleSister: OlderSiblingDelegate {
func getYourNiceOlderSiblingAGlassOfWater() {
// Little sis follows the letter of the law (ie, protocol),
// but no one said exactly how she had to respond.
print("Go get it yourself!")
}
}
// MARK: The Story
// Big bro is laying on the couch watching basketball on TV.
let bigBro = BossyBigBrother()
// He has a little sister named Sally.
let sally = PoorLittleSister()
// Sally walks into the room. How convenient! Now big bro
// has someone there to boss around.
bigBro.delegate = sally
// So he tells her to get him some water.
bigBro.tellSomebodyToGetMeSomeWater()
// Unfortunately no one lived happily ever after...
// The end.
In review, there are three key parts to making and using the delegate pattern.
In comparison to our Bossy Big Brother story above, delegates are often used for the following practical applications:
The great part is that these classes don't need to know anything about each other beforehand except that the delegate class conforms to the required protocol.
I highly recommend reading the following two articles. They helped me understand delegates even better than the documentation did.
One more note
Delegates that reference other classes that they do not own should use the weak
keyword to avoid strong reference cycles. See this answer for more details.
The jsonlite package is easy to use and tries to convert json into data frames.
Example:
library(jsonlite)
# url with some information about project in Andalussia
url <- 'http://www.juntadeandalucia.es/export/drupaljda/ayudas.json'
# read url and convert to data.frame
document <- fromJSON(txt=url)
Given issues with filter_var() needing http://, I use:
$is_url = filter_var($filename, FILTER_VALIDATE_URL) || array_key_exists('scheme', parse_url($filename));
Both pod and container are ephemeral, try to use the following command to stop the specific container and the k8s cluster will restart a new container.
kubectl exec -it [POD_NAME] -c [CONTAINER_NAME] -- /bin/sh -c "kill 1"
This will send a SIGTERM
signal to process 1, which is the main process running in the container. All other processes will be children of process 1, and will be terminated after process 1 exits. See the kill manpage for other signals you can send.
In currently latest JDK6 release/build (b27), the Scanner
has a smaller buffer (1024 chars) as opposed to the BufferedReader
(8192 chars), but it's more than sufficient.
As to the choice, use the Scanner
if you want to parse the file, use the BufferedReader
if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.
nextXxx()
methods in Scanner
class. Random function from the sql could help. Also if you would like to limit to just one row, just add that in the end.
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
As Paddy mentioned: if you use an overload of UrlHelper.Action()
that explicitly specifies the protocol to use, the generated URL will be absolute and fully qualified instead of being relative.
I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I suggest to write a custom extension method for the sake of readability:
/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
string actionName, string controllerName, object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
You can then simply use it like that in your view:
@Url.AbsoluteAction("Action", "Controller")
best and simple way is to put title inside a span and replace then.
'<div id="'+div_id+'" class="widget" style="height:60px;width:110px">\n\
<div class="widget-head ui-widget-header"
style="cursor:move;height:20px;width:130px">'+
'<span id="'+span_id+'" style="float:right; cursor:pointer"
class="dialog_link ui-icon ui-icon-newwin ui-icon-pencil"></span>' +
'<span id="spTitle">'+
dialog_title+ '</span>'
'</div></div>
now you can simply use this:
$('#'+div_id+' .widget-head sp#spTitle').text("new dialog title");
The is
operator in Python probably doesn't do what you expect. Instead of this:
if numpy.array_equal(tmp,universe_array) is True:
break
I would write it like this:
if numpy.array_equal(tmp,universe_array):
break
The is
operator tests object identity, which is something quite different from equality.
It seems like You haven't set the Mysql server path, Set Environment Variable For MySql Server. Then restart the command prompt and enter mysql -u root-p then it asks for a password enter it. Thank you. Happy learning!
int max = 50;
int min = 1;
double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);
This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double
Why?
random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.
Random rand = new Random();
int value = rand.nextInt(50);
This will give value from 0 to 49.
For 1 to 50: rand.nextInt((max - min) + 1) + min;
Source of some Java Random awesomeness.
Angularjs Dependency Injection framework is responsible for injecting the dependancies of you app module to your controllers. This is possible through its injector.
You need to first identify the ng-app and get the associated injector. The below query works to find your ng-app in the DOM and retrieve the injector.
angular.element('*[ng-app]').injector()
In chrome, however, you can point to target ng-app as shown below. and use the $0
hack and issue angular.element($0).injector()
Once you have the injector, get any dependency injected service as below
injector = angular.element($0).injector();
injector.get('$mdToast');
Alternate method to run 32-bit scripts on 64-bit machine: %windir%\syswow64\cscript.exe vbscriptfile.vbs
It is a reference to the current file name. In the file foo.rb
, __FILE__
would be interpreted as "foo.rb"
.
Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:
# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__
Running ruby test.rb
will output
test.rb
/full/path/to/dir2/test.rb
transform
translateX
/translateY
:Example Here / Full Screen Example
In supported browsers (most of them), you can use top: 50%
/left: 50%
in combination with translateX(-50%) translateY(-50%)
to dynamically vertically/horizontally center the element.
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
Example Here / Full Screen Example
In supported browsers, set the display
of the targeted element to flex
and use align-items: center
for vertical centering and justify-content: center
for horizontal centering. Just don't forget to add vendor prefixes for additional browser support (see example).
html, body, .container {
height: 100%;
}
.container {
display: flex;
align-items: center;
justify-content: center;
}
table-cell
/vertical-align: middle
:Example Here / Full Screen Example
In some cases, you will need to ensure that the html
/body
element's height is set to 100%
.
For vertical alignment, set the parent element's width
/height
to 100%
and add display: table
. Then for the child element, change the display
to table-cell
and add vertical-align: middle
.
For horizontal centering, you could either add text-align: center
to center the text and any other inline
children elements. Alternatively, you could use margin: 0 auto
assuming the element is block
level.
html, body {
height: 100%;
}
.parent {
width: 100%;
height: 100%;
display: table;
text-align: center;
}
.parent > .child {
display: table-cell;
vertical-align: middle;
}
50%
from the top with displacement:Example Here / Full Screen Example
This approach assumes that the text has a known height - in this instance, 18px
. Just absolutely position the element 50%
from the top, relative to the parent element. Use a negative margin-top
value that is half of the element's known height, in this case - -9px
.
html, body, .container {
height: 100%;
}
.container {
position: relative;
text-align: center;
}
.container > p {
position: absolute;
top: 50%;
left: 0;
right: 0;
margin-top: -9px;
}
line-height
method (Least flexible - not suggested):In some cases, the parent element will have a fixed height. For vertical centering, all you have to do is set a line-height
value on the child element equal to the fixed height of the parent element.
Though this solution will work in some cases, it's worth noting that it won't work when there are multiple lines of text - like this.
.parent {
height: 200px;
width: 400px;
text-align: center;
}
.parent > .child {
line-height: 200px;
}
Methods 4 and 5 aren't the most reliable. Go with one of the first 3.
This works if you already have or set up the rename command (e.g. through brew install in Mac):
rename --lower-case --force somedir/*
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
0
\u0000
or 0
0.0
false
null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
Here is two examples, one print the logs (stdout) the other write the logs to a file:
import logging
import sys
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)
file_handler = logging.FileHandler('logs.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stdout_handler)
With this example, all logs will be printed and also be written to a file named logs.log
Use example:
logger.info('This is a log message!')
logger.error('This is an error message.')
You can use the following list as quick reference:
/ = Root directory
. = This location
.. = Up a directory
./ = Current directory
../ = Parent of current directory
../../ = Two directories backwards
Useful article: https://css-tricks.com/quick-reminder-about-file-paths/
just call the finish() in the method you would like to end the activity in, for example when you use the onCreate() method, in the end of the method, just add finish() and you will see the activity ends as soon as it is created!
tqdm: add a progress meter to your loops in a second:
>>> import time
>>> from tqdm import tqdm
>>> for i in tqdm(range(100)):
... time.sleep(1)
...
|###-------| 35/100 35% [elapsed: 00:35 left: 01:05, 1.00 iters/sec]
I think your problem is your version numbers. Try making 8.1 --> 8.01, and so forth. That should put the points in the right order.
Alternatively, you could plot using X
, where X is the column number you want, instead of using 1:X
. That will plot those values on the y axis and integers on the x axis. Try:
plot "ls.dat" using 2 title 'Removed' with lines, \
"ls.dat" using 3 title 'Added' with lines, \
"ls.dat" using 4 title 'Modified' with lines
You can use the grid
feature for the second unused axis x2
, which is the most natural way of drawing a set of regular spaced lines.
set grid x2tics
set x2tics 10 format "" scale 0
In general, the grid is drawn at the same position as the tics on the axis. In case the position of the lines does not correspond to the tics position, gnuplot provides an additional set of tics, called x2tics
. format ""
and scale 0
hides the x2tics so you only see the grid lines.
You can style the lines as usual with linewith
, linecolor
.
TabPanel1.Visible = true; // Show Tabpage 1
TabPanel1.Visible = false; //Hide Tabpage 1
If your goal is to make sure "the user won't be confused at all," I think this is the best option.
I wouldn't recommend a datepicker for date of birth. First you have to browse to the year (click, click, click…), then to the month (click some more), and then find and click the tiny number on a grid.
Datepickers are useful when you don't know the exact date off the top of your head, e.g. you're planning a trip for the second week of February.
We are running Linux, a mostly POSIX-compliant OS. POSIX standards it should be: Utility Argument Syntax.
-o
. -o argument
or
-oargument
. -lst
is equivalent to -t -l -s
.-lst
is equivalent to -tls
.-lst
nonoption.--
argument terminates options.-
option is typically used to represent one of the standard input
streams.#!/usr/bin/python2
import sys, subprocess, threading
proc = subprocess.Popen(sys.argv[2:])
timer = threading.Timer(float(sys.argv[1]), proc.terminate)
timer.start()
proc.wait()
timer.cancel()
exit(proc.returncode)
IF CHARINDEX('TextToSearch',@TextWhereISearch, 0) > 0 => TEXT EXISTS
IF PATINDEX('TextToSearch', @TextWhereISearch) > 0 => TEXT EXISTS
Additionally we can also use LIKE but I usually don't use LIKE.
function getDomain(url, subdomain) {
subdomain = subdomain || false;
url = url.replace(/(https?:\/\/)?(www.)?/i, '');
if (!subdomain) {
url = url.split('.');
url = url.slice(url.length - 2).join('.');
}
if (url.indexOf('/') !== -1) {
return url.split('/')[0];
}
return url;
}
Examples
Previous version was getting full domain (including subdomain). Now it determines the right domain depending on preference. So that when a 2nd argument is provided as true it will include the subdomain, otherwise it returns only the 'main domain'
Converting from dict to list is made easy in Python. Three examples:
>> d = {'a': 'Arthur', 'b': 'Belling'}
>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]
>> d.keys()
['a', 'b']
>> d.values()
['Arthur', 'Belling']
If you are totally new to python read step by step or go directly to 5th step directly. Follow the below method to install scipy 0.18.1 on Windows 64-bit , Python 64-bit . Be careful with the versions of 1. Python 2. Windows 3. .whl version of numpy and scipy files 4. First install numpy and then scipy.
pip install FileName.whl
Be aware of the file name ( what I mean is check the cp no). Ex :scipy-0.18.1-cp35-cp35m-win_amd64.whl To check which cp is supported by your pip , go to point No 2 below.
If you are using .whl file . Following errors are likely to occur .
- You are using pip version 7.1.0, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command
- scipy-0.15.1-cp33-none-win_amd64.whl.whl is not supported wheel on this platform
For the above error : start Python(in my case 3.5), type :
import pip
print(pip.pep425tags.get_supported())
output :
[('cp35', 'cp35m', 'win_amd64'), ('cp35', 'none', 'win_amd64'), ('py3', 'none', 'win_amd64'), ('cp35', 'none', 'any'), ('cp3', 'none', 'any'), ('py35', 'none', 'any'), ('py3', 'none', 'any'), ('py34', 'none', 'any'), ('py33', 'none', 'any'), ('py32', 'none', 'any'), ('py31', 'none', 'any'), ('py30', 'none', 'any')]
In the output you will observe cp35 is there , so download cp35 for numpy as well as scipy. Further edits are most welcome !!!!
Use sqlite3 database.sqlite3 < db.sql
. You'll need to make sure that your files contain valid SQL for SQLite.
I know this post is old but I just wanted to add my answer!
You said to log a user out WITHOUT directing... this method DOES redirect but it returns the user to the page they were on! here's my implementation:
// every page with logout button
<?php
// get the full url of current page
$page = $_SERVER['PHP_SELF'];
// find position of the last '/'
$file_name_begin_pos = strripos($page, "/");
// get substring from position to end
$file_name = substr($page, ++$fileNamePos);
}
?>
// the logout link in your html
<a href="logout.php?redirect_to=<?=$file_name?>">Log Out</a>
// logout.php page
<?php
session_start();
$_SESSION = array();
session_destroy();
$page = "index.php";
if(isset($_GET["redirect_to"])){
$file = $_GET["redirect_to"];
if ($file == "user.php"){
// if redirect to is a restricted page, redirect to index
$file = "index.php";
}
}
header("Location: $file");
?>
and there we go!
the code that gets the file name from the full url isn't bug proof. for example if query strings are involved with un-escaped '/' in them, it will fail.
However there are many scripts out there to get the filename from url!
Happy Coding!
Alex
The arguments is an array-like object (not an actual array). Example function...
function testArguments () // <-- notice no arguments specified
{
console.log(arguments); // outputs the arguments to the console
var htmlOutput = "";
for (var i=0; i < arguments.length; i++) {
htmlOutput += '<li>' + arguments[i] + '</li>';
}
document.write('<ul>' + htmlOutput + '</ul>');
}
Try it out...
testArguments("This", "is", "a", "test"); // outputs ["This","is","a","test"]
testArguments(1,2,3,4,5,6,7,8,9); // outputs [1,2,3,4,5,6,7,8,9]
The full details: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments
Allocate maximum memory to your docker machine from (docker preference -> advance )
Screenshot of advance settings:
This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.
docker run -m=4g {imageID}
Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.
Your pip
is a soft link to the same executable file path with pip3
.
you can use the commands below to check where your pip
and pip3
real paths are:
$ ls -l `which pip`
$ ls -l `which pip3`
You may also use the commands below to know more details:
$ pip show pip
$ pip3 show pip
When we install different versions of python, we may create such soft links to
It is the same situation with python
, python2
, python3
More information below if you're interested in how it happens in different cases:
For SQL Server 2005+
;WITH T AS
(
SELECT *,
COUNT(*) OVER (PARTITION BY Lastname) as Cnt
FROM Students
)
SELECT * /*TODO: Add column list. Don't use "*" */
FROM T
WHERE Cnt >= 3
The same problem plagues Visual Studios 2013, Service Pack 4. I also tried it with Visual Studios 2015 Preview with the same results.
It's just a limitation of the WPF visualizer which the Visual Studios team hasn't fixed. As proof, building in x86 mode enables the visualizer and building in x64 mode disables it.
Strangely enough intellisense works for Visual Studios 2013, Service Pack 4.
You should write a kind of template into the @RequestMapping
:
http://localhost:8080/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}
Now define your business method like following:
@RequestMapping("/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}")
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "search") String search,
@RequestParam(value = "nd") int nd,
@RequestParam(value = "rows") int rows,
@RequestParam(value = "page") int page,
@RequestParam(value = "sidx") int sidx,
@RequestParam(value = "sort") Sort sort) {
...............
}
So, framework will map ${foo}
to appropriate @RequestParam
.
Since sort may be either asc or desc I'd define it as a enum:
public enum Sort {
asc, desc
}
Spring deals with enums very well.
The best option is to use the original LESS version of bootstrap (get it from github).
Open variables.less and look for // Media queries breakpoints
Find this code and change the breakpoint value:
// Large screen / wide desktop
@screen-lg: 1200px; // change this
@screen-lg-desktop: @screen-lg;
Change it to 9999px for example, and this will prevent the breakpoint to be reached, so your site will always load the previous media query which has 940px container
You need to indicate the groupId, the artifactId and the version for your artifact:
mvn install:install-file \
-DgroupId=javax.transaction \
-DartifactId=jta \
-Dpackaging=jar \
-Dversion=1.0.1B \
-Dfile=jta-1.0.1B.jar \
-DgeneratePom=true
Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:
using Newtonsoft.Json;
...
var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://api.clickatell.com/rest/message"),
Headers = {
{ HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
{ HttpRequestHeader.Accept.ToString(), "application/json" },
{ "X-Version", "1" }
},
Content = new StringContent(JsonConvert.SerializeObject(svm))
};
var response = client.SendAsync(httpRequestMessage).Result;
You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.
For getting the result you have to add a lil things in your script like
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
//echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
This will give you result;
Note that in case of Internet Explorer 7 and Internet Explorer 9 the if
statment will give true (for "onhashchange" in windows), but the window.onhashchange
will never fire, so it's better to store hash and check it after every 100 millisecond whether it's changed or not for all versions of Internet Explorer.
if (("onhashchange" in window) && !($.browser.msie)) {
window.onhashchange = function () {
alert(window.location.hash);
}
// Or $(window).bind( 'hashchange',function(e) {
// alert(window.location.hash);
// });
}
else {
var prevHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != prevHash) {
prevHash = window.location.hash;
alert(window.location.hash);
}
}, 100);
}
EDIT -
Since jQuery 1.9, $.browser.msie
is not supported. Source: http://api.jquery.com/jquery.browser/
All these tips did not work for me, what worked was cloning over ssh rather that http
@Entity(name = "someThing") => this name will be used to name the Entity @Table(name = "someThing") => this name will be used to name a table in DB
So, in the first case your table and entity will have the same name, that will allow you to access your table with the same name as the entity while writing HQL or JPQL.
And in second case while writing queries you have to use the name given in @Entity and the name given in @Table will be used to name the table in the DB.
So in HQL your someThing will refer to otherThing in the DB.
Another possible solution: create an object containing the group names and indexes.
var regex = new RegExp("(.*) (.*)");
var regexGroups = { FirstName: 1, LastName: 2 };
Then, use the object keys to reference the groups:
var m = regex.exec("John Smith");
var f = m[regexGroups.FirstName];
This improves the readability/quality of the code using the results of the regex, but not the readability of the regex itself.
Heard you can do this in postman:
You can use {!! $text !!} for render HTML code in Laravel
{!! $text !!}
If you use
{{ $text }}
It will not render HTML code and print as a string.
It surprises me that no one mentioned the key difference between these two is that the temp table supports parallel insert while the table variable doesn't. You should be able to see the difference from the execution plan. And here is the video from SQL Workshops on Channel 9.
This also explains why you should use a table variable for smaller tables, otherwise use a temp table, as SQLMenace answered before.
A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.
import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
fig, ax = plt.subplots(figsize=(10, 8))
# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))
# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')
Put the loops in a subroutine and call return
You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save().
Basically, a field declared as a FileField
, when accessed, gives you an instance of class FieldFile
, which gives you several methods to interact with the underlying file. So, what you need to do is:
self.license_file.save(new_name, new_contents)
where new_name
is the filename you wish assigned and new_contents
is the content of the file. Note that new_contents
must be an instance of either django.core.files.File
or django.core.files.base.ContentFile
(see given links to manual for the details).
The two choices boil down to:
from django.core.files.base import ContentFile, File
# Using File
with open('/path/to/file') as f:
self.license_file.save(new_name, File(f))
# Using ContentFile
self.license_file.save(new_name, ContentFile('A string with the file content'))
I believe the simplest solution would be to use find
. I do not like to have multiple .gitignore
hanging around in sub-directories and I prefer to manage a unique, top-level .gitignore
. To do so you could simply append the found files to your .gitignore
. Supposing that /public/static/
is your project/git home I would use something like:
find . -type f -name *.js | cut -c 3- >> .gitignore
I found that cutting out the ./
at the beginning is often necessary for git to understand which files to avoid. Therefore the cut -c 3-
.
If you get this error while compiling in Microsoft Mobile Center
? Code signing is required for product type 'Application' in SDK 'iOS 10.3'
** ARCHIVE FAILED **
be aware that Mobile center doesn't yet support automatic signing with certificates of type app-store, ad-hoc and enterprise. Automatic signing only works with development certificates.
There are two things you can do to work around that limitation:
Use a development certificate. You'll have to create a new one in the developer.apple.com portal, download it to your machine, export it to a .p12 file using keychain, then finally provide it to Mobile Center. You know the drill.
Disable automatic signing. You will find that setting in Xcode in your project targets. Once disabled, a little "i" button will be displayed next to the "Xcode managed profile" label. Click that button, some info about the profile will be displayed. On the top left corner of that window, a "PROV" icon is displayed. That is the provisioning profile that you should provide to Mobile Center. Drag and drop the icon into the corresponding field in Mobile Center.
Besides maintainability, the first way eliminates possibility of accident global variables creation:
(function () {
var variable1 = "Hello, World!" // Semicolon is missed out accidentally
var variable2 = "Testing..."; // Still a local variable
var variable3 = 42;
}());
While the second way is less forgiving:
(function () {
var variable1 = "Hello, World!" // Comma is missed out accidentally
variable2 = "Testing...", // Becomes a global variable
variable3 = 42; // A global variable as well
}());
I ran into the issue where the class of 'selected' wasn't being added to my menu item. Turns out that you can't have a NavigateUrl on it for whatever reason.
Once I removed the NavigateUrl it applied the 'selected' css class to the a tag and I was able to apply the background style with:
div.menu ul li a.static.selected
{
background-color: #bfcbd6 !important;
color: #465c71 !important;
text-decoration: none !important;
}
Use the format()
function with a '02x'
format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02
part tells format()
to use at least 2 digits and to use zeros to pad it to length, x
means lower-case hexadecimal.
The Format Specification Mini Language also gives you X
for uppercase hex output, and you can prefix the field width with #
to include a 0x
or 0X
prefix (depending on wether you used x
or X
as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.
<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
jQuery("#" + id).html(jQuery("#loading").html());
jQuery("#" + id).show();
}
In my case I had declared the following property in one of my ViewControllers subclass:
@property NSString * title
I think this was conflicting with the already existing title
property in ViewController
. I renamed this property to something else and refactored its use and the error disappeared.
add like
<head runat="server">
<script src="Registration.js" type="text/javascript"></script>
</head>
OR can add in code behind.
Page.ClientScript.RegisterClientScriptInclude("Registration", ResolveUrl("~/js/Registration.js"));
#include <stdio.h>
#include <stdlib.h>
int func(char a, char b, char c) /* demonstration that char on stack is promoted to int !!!
note: this promotion is NOT integer promotion, but promotion during handling of the stack. don't confuse the two */
{
const char *p = &a;
printf("a=%d\n"
"b=%d\n"
"c=%d\n", *p, p[-(int)sizeof(int)], p[-(int)sizeof(int) * 2]); // don't do this. might probably work on x86 with gcc (but again: don't do this)
}
int main(void)
{
func(1, 2, 3);
//printf with %d treats its argument as int (argument must be int or smaller -> works because of conversion to int when on stack -- see demo above)
printf("%d, %d, %d\n", (long long) 1, 2, 3); // don't do this! Argument must be int or smaller type (like char... which is converted to int when on the stack -- see above)
// backslash followed by number is a oct VALUE
printf("%d\n", '\377'); /* prints -1 -> IF char is signed char: char literal has all bits set and is thus value -1.
-> char literal is then integer promoted to int. (this promotion has nothing to do with the stack. don't confuse the two!!!) */
/* prints 255 -> IF char is unsigned char: char literal has all bits set and is thus value 255.
-> char literal is then integer promoted to int */
// backslash followed by x is a hex VALUE
printf("%d\n", '\xff'); /* prints -1 -> IF char is signed char: char literal has all bits set and is thus value -1.
-> char literal is then integer promoted to int */
/* prints 255 -> IF char is unsigned char: char literal has all bits set and is thus value 255.
-> char literal is then integer promoted to int */
printf("%d\n", 255); // prints 255
printf("%d\n", (char)255); // prints -1 -> 255 is cast to char where it is -1
printf("%d\n", '\n'); // prints 10 -> Ascii newline has VALUE 10. The char 10 is integer promoted to int 10
printf("%d\n", sizeof('\n')); // prints 4 -> Ascii newline is char, but integer promoted to int. And sizeof(int) is 4 (on many architectures)
printf("%d\n", sizeof((char)'\n')); // prints 1 -> Switch off integer promotion via cast!
return 0;
}
I found that this works if wanting in a (123) - 456-7890 format.
UPDATE table
SET Phone_number = '(' +
SUBSTRING(Phone_number, 1, 3)
+ ') '
+ '- ' +
SUBSTRING(Phone_number, 4, 3)
+ '-' +
SUBSTRING(Phone_number, 7, 4)
You can use java.lang.Runtime.exec
to run simple code. This gives you back a Process
and you can read its standard output directly without having to temporarily store the output on disk.
For example, here's a complete program that will showcase how to do it:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class testprog {
public static void main(String args[]) {
String s;
Process p;
try {
p = Runtime.getRuntime().exec("ls -aF");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
}
When compiled and run, it outputs:
line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0
as expected.
You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).
If you want to merge the process standard output and error from Java (as opposed to using 2>&1
in the actual command), you should look into ProcessBuilder
.
You can also make your own nodeJS endpoint, publish it with something like heroku, and access it
require("http").createServer(function (q,r) {
r.setHeader("accees-control-allow-origin","*")
r.end(Date.now())
}).listen(process.env.PORT || 80)
Then just access it on JS
fetch ("http://someGerokuApp")
.then(r=>r.text)
. then (r=>console.log(r))
This will still be relative to whatever computer the node app is hosted on, but perhaps you can get the location somehow and provide different endpoints fit the other timezones based on the current one (for example if the server happens to be in California then for a new York timezone just add 1000*60*60*3
milliseconds to Date.now() to add 3 hours)
For simplicity, if it's possible to get the location from the server and send it as a response header, you can just do the calculations for the different time zones in the client side
In fact using heroku they allow you to specify a region that it should be deployed at https://devcenter.heroku.com/articles/regions#specifying-a-region you can use this as reference..
EDIT just realized the timezone is in the date string itself, can just pay the whole thing as a header to be read by the client
require("http").createServer(function (q,r) {
var d= new Date()
r.setHeader("accees-control-allow-origin","*")
r.setHeader("zman", d.toString())
r.end(d.getTime())
}).listen(process.env.PORT || 80)
This answer may be out of topic for most of readers. In my case the dependency didn't update and "mvn clean" didn't work since my wifi network at the office is highly securised, leaving a "connection timed out". (same respect github pushes and pulls don't work) I just moved to teathering with my phone and it works. Stupid, out of topic for most, but it may help some very specific cases.
The following code is used in Visual Basic when prompting a user to exit the application:
Dim D As String
D = MsgBox("Are you sure you want to exit?", vbYesNo+vbQuestion,"Thanking You")
If D = vbYes Then
Unload Me
Else
Exit Sub
End If
End
End Sub
This is not so helpful if you need to just know the month name for a given number (1 - 12), as the current day doesn't matter.
calendar.month_name[i]
or
calendar.month_abbr[i]
are more useful here.
Here is an example:
import calendar
for month_idx in range(1, 13):
print (calendar.month_name[month_idx])
print (calendar.month_abbr[month_idx])
print ("")
Sample output:
January
Jan
February
Feb
March
Mar
...
You can use the :checkbox
and :checked
pseudo-selectors and the .class
selector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.
Then you can easily use the Traversing/map method to get an array of values:
var values = $('input:checkbox:checked.group1').map(function () {
return this.value;
}).get(); // ["18", "55", "10"]
The root directory for the loader is in the 'resources' folder for a maven project. So if you have src/main/java
then the fxml file path should start from:
src/main/resources
https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
Try this
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
@Override
public void run() {
//your code here that talks with the UI level widgets/ try to access the UI
//elements from this block because this piece of snippet will run in the UI/MainThread.
}
});
Update 2018, SDK >= 23.
Now you should also check if the user has granted permission to external storage by using:
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
public void saveImageBitmap(Bitmap image_bitmap, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
if (isStoragePermissionGranted()) { // check or ask permission
File myDir = new File(root, "/saved_images");
if (!myDir.exists()) {
myDir.mkdirs();
}
String fname = "Image-" + image_name + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile(); // if file already exists will do nothing
FileOutputStream out = new FileOutputStream(file);
image_bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, new String[]{file.getName()}, null);
}
}
and of course, add in the AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}
I used this code to solve this problem.
<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>
You can check the tweet-button documentation here tweet-button
since you only want the files, you don't need to treat it as a git repo.
rsync -rlp --exclude '.git' user@host:path/to/git/repo/ .
and this only works with local path and remote ssh/rsync path, it may not work if the remote server only provides git:// or https:// access.
Well, you don't want to execute 1000 query calls, but doing this is fine:
$stmt= array( 'array of statements' );
$query= 'INSERT INTO yourtable (col1,col2,col3) VALUES ';
foreach( $stmt AS $k => $v ) {
$query.= '(' .$v. ')'; // NOTE: you'll have to change to suit
if ( $k !== sizeof($stmt)-1 ) $query.= ', ';
}
$r= mysql_query($query);
Depending on your data source, populating the array might be as easy as opening a file and dumping the contents into an array via file()
.
In Visual Studio 2015 (Soulution is under source control, MVC-Project), csano's Update-Package -Reinstall -ProjectName Your.Project.Name
worked, but it messed up with some write locks.
I had to delete the "packages"-Folder manually before. (It seemed to be locked because of the source control).
Also, I had to re-install the MVC-Package from the NuGet Package Manager.
There is nothing wrong in concatenating two strings with +
. Indeed it's easier to read than ''.join([a, b])
.
You are right though that concatenating more than 2 strings with +
is an O(n^2) operation (compared to O(n) for join
) and thus becomes inefficient. However this has not to do with using a loop. Even a + b + c + ...
is O(n^2), the reason being that each concatenation produces a new string.
CPython2.4 and above try to mitigate that, but it's still advisable to use join
when concatenating more than 2 strings.
You can call the function from code behind like this :
MyForm.aspx.cs
protected void MyButton_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}
MyForm.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Test() {
alert("hi");
$("#ButtonRow").show();
}
function AnotherFunction()
{
alert("This is another function");
}
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
<tr><td>
<asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()" RepeatDirection="Horizontal" BorderStyle="Solid">
<asp:ListItem>Merchant</asp:ListItem>
<asp:ListItem>Store</asp:ListItem>
<asp:ListItem>Terminal</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr id="ButtonRow"style="display:none">
<td>
<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
</td>
</tr>
</table>
</form>
—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:
{{#variable}}<span class="text">{{.}}</span>{{/variable}}
The line onclick = writeLED(1,1)
means that you want to immediately execute the function writeLED(arg1, arg2) with arguments 1, 1 and assign the return value; you need to instead create a function that will execute with those arguments and assign that. The topmost answer gave one example - another is to use the bind() function like so:
var writeLEDWithSpecifiedArguments = writeLED.bind(this, 1,1);
document.getElementById('buttonLED'+id).onclick = writeLEDWithSpecifiedArguments;
Visibility change itself can be easy animated by overriding setVisibility method. Look at complete code:
public class SimpleViewAnimator extends FrameLayout
{
private Animation inAnimation;
private Animation outAnimation;
public SimpleViewAnimator(Context context)
{
super(context);
}
public void setInAnimation(Animation inAnimation)
{
this.inAnimation = inAnimation;
}
public void setOutAnimation(Animation outAnimation)
{
this.outAnimation = outAnimation;
}
@Override
public void setVisibility(int visibility)
{
if (getVisibility() != visibility)
{
if (visibility == VISIBLE)
{
if (inAnimation != null) startAnimation(inAnimation);
}
else if ((visibility == INVISIBLE) || (visibility == GONE))
{
if (outAnimation != null) startAnimation(outAnimation);
}
}
super.setVisibility(visibility);
}
}
To change locally for just one repository, enter in terminal, from within the repository
git config credential.username "new_username"
To change globally use
git config --global credential.username "new_username"
(EDIT EXPLAINED: If you don't change also the user.email
and user.name
, you will be able to push your changes, but they will be registered in git under the previous user)
Next time you push
, you will be asked to enter your password
Password for 'https://<new_username>@github.com':
if you want to get "terse" :)
List<string>GlobalStrings = new List<string>();
for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});
Just need to change one letter:), rename 640x360.ogv to 640x360.ogg, it will work for all the 3 browers.
public class ConfigureActivity extends Activity {
EditText etOne;
EditText etTwo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configure);
Button btnConfigure = findViewById(R.id.btnConfigure1);
btnConfigure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
configure();
}
});
}
public void configure(){
String one = etOne.getText().toString();
String two = etTwo.getText().toString();
}
}
you have to name your checkboxes accordingly:
<input type="checkbox" name="check_list[]" value="…" />
you can then access all checked checkboxes with
// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
// do something
}
ps. make sure to properly escape your output (htmlspecialchars()
)
Variations on a theme:
NSString *varying = @"whatever it is";
NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying];
NSString *varying = @"whatever it is";
NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"];
NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendFormat:@"%@ third part", varying];
NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendString:varying];
[final appendString:@"third part"];
You can put the values as the table's keys. For example:
function addToSet(set, key)
set[key] = true
end
function removeFromSet(set, key)
set[key] = nil
end
function setContains(set, key)
return set[key] ~= nil
end
There's a more fully-featured example here.
This script iterates all directories and zip each one
Get-ChildItem -Attributes d | foreach {write-zip $.Name "$($.Name).zip"}
with itertools.product:
import itertools
result = list(itertools.product(*somelists))
get-aduser -Server "servername" -Identity %username% -Properties *
get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *
These work when you have the username. Also less to type than using the -filter
property.
EDIT: Formatting.
First, please remember that in a Mac computer the netbeans.conf file is stored at
/Applications/NetBeans/NetBeans 8.2.app/Contents/Resources/NetBeans/etc/netbeans.conf
(if you had used the default installation package.)
Then, also remember that the directory you MUST use on either "netbeans_jdkhome" or "--jdkhome" it's NOT the /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/ but the following one:
/Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home //<-- Please, notice the /Contents/Home at the end. That's the "trick"!
Note: of course, you must change the versions for both NetBeans and JDK you're using.
If you want implications, in some scenarios Google Chrome performance is horrible with hardware acceleration enabled. Oddly enough, changing the "trick" to -webkit-transform: rotateZ(360deg);
worked just fine.
I don't believe we ever figured out why.
This is a little late for this question but others might benefit. I had a similar problem but had an added requirement for the text to correctly wrap in all device sizes. So in my case this worked. Need to setup the view port.
.p
{
white-space: normal;
overflow-wrap: break-word;
width: 96vw;
}
This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).
The markup
<table class="table">
<thead>
<tr>
<th>
<input type="checkbox"
ng-click="selectAll($event)"
ng-checked="isSelectedAll()">
</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
<td>
<input type="checkbox" name="selected"
ng-checked="isSelected(e.id)"
ng-click="updateSelection($event, e.id)">
</td>
<td>{{e.title}}</td>
</tr>
</tbody>
</table>
And in the controller
var updateSelected = function(action, id) {
if (action === 'add' && $scope.selected.indexOf(id) === -1) {
$scope.selected.push(id);
}
if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
$scope.selected.splice($scope.selected.indexOf(id), 1);
}
};
$scope.updateSelection = function($event, id) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
updateSelected(action, id);
};
$scope.selectAll = function($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
for ( var i = 0; i < $scope.entities.length; i++) {
var entity = $scope.entities[i];
updateSelected(action, entity.id);
}
};
$scope.getSelectedClass = function(entity) {
return $scope.isSelected(entity.id) ? 'selected' : '';
};
$scope.isSelected = function(id) {
return $scope.selected.indexOf(id) >= 0;
};
//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
return $scope.selected.length === $scope.entities.length;
};
EDIT: getSelectedClass()
expects the entire entity but it was being called with the id of the entity only, which is now corrected
Pass the id that you want to remove from the array to the given function
from the controller( Function can be in the same controller but prefer to keep it in a service)
function removeInfo(id) {
let item = bdays.filter(function(item) {
return bdays.id=== id;
})[0];
let index = bdays.indexOf(item);
data.device.splice(indexOfTabDetails, 1);
}
The UPDATE syntax is:
[ WITH [ RECURSIVE ] with_query [, ...] ] UPDATE [ ONLY ] table [ [ AS ] alias ] SET { column = { expression | DEFAULT } | ( column [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...] [ FROM from_list ] [ WHERE condition | WHERE CURRENT OF cursor_name ] [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]
In your case I think you want this:
UPDATE vehicles_vehicle AS v
SET price = s.price_per_vehicle
FROM shipments_shipment AS s
WHERE v.shipment_id = s.id
In C, this is done using arguments passed to your main()
function:
int main(int argc, char *argv[])
{
int i = 0;
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
More information can be found online such as this Arguments to main article.
Thought I'd put in my two bits here since I have just figured out how this works.
It appears that you don't have the port specified on your SERVER connection settings, this effected me a little bit when I was trying to connect to my SMTP server that isn't using the default port: 25.
According to the smtplib.SMTP docs, your ehlo or helo request/response should automatically be taken care of, so you shouldn't have to worry about this (but might be something to confirm if all else fails).
Another thing to ask yourself is have you allowed SMTP connections on your SMTP server itself? For some sites like GMAIL and ZOHO you have to actually go in and activate the IMAP connections within the email account. Your mail server might not allow SMTP connections that don't come from 'localhost' perhaps? Something to look into.
The final thing is you might want to try and initiate the connection on TLS. Most servers now require this type of authentication.
You'll see I've jammed two TO fields into my email. The msg['TO'] and msg['FROM'] msg dictionary items allows the correct information to show up in the headers of the email itself, which one sees on the receiving end of the email in the To/From fields (you might even be able to add a Reply To field in here. The TO and FROM fields themselves are what the server requires. I know I've heard of some email servers rejecting emails if they don't have the proper email headers in place.
This is the code I've used, in a function, that works for me to email the content of a *.txt file using my local computer and a remote SMTP server (ZOHO as shown):
def emailResults(folder, filename):
# body of the message
doc = folder + filename + '.txt'
with open(doc, 'r') as readText:
msg = MIMEText(readText.read())
# headers
TO = '[email protected]'
msg['To'] = TO
FROM = '[email protected]'
msg['From'] = FROM
msg['Subject'] = 'email subject |' + filename
# SMTP
send = smtplib.SMTP('smtp.zoho.com', 587)
send.starttls()
send.login('[email protected]', 'password')
send.sendmail(FROM, TO, msg.as_string())
send.quit()
In case you need to parse it from a file, I find the best solution to use a HashMap<String, String>
to use it inside your java code for better manipultion.
Try out this code:
public HashMap<String, String> myMethodName() throws FileNotFoundException
{
String path = "absolute path to your file";
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
Gson gson = new Gson();
HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
return json;
}
Try following code snippet.
double myVal = 0;
String myVar = "Not Numeric Type";
if (Double.TryParse(myVar , out myNum)) {
// it is a number
} else {
// it is not a number
}
PowerBI Embedded requires TLS 1.2.
The answer above by Etienne Faucher is your solution. quick link to above answer... quick link to above answer... ( https://stackoverflow.com/a/45442874 )
PowerBI Requires TLS 1.2 June 2020 - This Is your Answer - Consider Forcing your IIS runtime to get up to 4.6 to force the default TLS 1.2 behavior you are looking for from the framework. The above answer gives you a config change only solution.
Symptoms: Forced Closed Rejected TCP/IP Connection to Microsoft PowerBI Embedded that just shows up all of a sudden across your systems.
These PowerBI Calls just stop working with a Hard TCP/IP Close error like a firewall would block a connection. Usually the auth steps work - it is when you hit the service for specific workspace and report id's that it fails.
This is the 2020 note from Microsoft PowerBI about TLS 1.2 required
PowerBIClient
methods that show this problem
GetReportsInGroupAsync GetReportsInGroupAsAdminAsync GetReportsAsync GetReportsAsAdminAsync Microsoft.PowerBI.Api HttpClientHandler Force TLS 1.1 TLS 1.2
Search Error Terms to help people find this: System.Net.Http.HttpRequestException: An error occurred while sending the request System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Here is a shorter implementation comparing to @Jav_Rock's
/**
* Round to certain number of decimals
*
* @param d
* @param decimalPlace the numbers of decimals
* @return
*/
public static float round(float d, int decimalPlace) {
return BigDecimal.valueOf(d).setScale(decimalPlace,BigDecimal.ROUND_HALF_UP).floatValue();
}
System.out.println(round(2.345f,2));//two decimal digits, //2.35
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
Let me try example
for x in 1 2 3 ; do { echo a $x ; sleep 1 ; echo b $x ; } & done ; sleep 10
And use jobs
to see what's running.
"Plain Old C# Object"
Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.
EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.
TO CLARIFY: In other words, they don’t derive from some special base class, nor do they return any special types for their properties.
See below for an example of each.
Example of a POCO:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Example of something that isn’t a POCO:
public class PersonComponent : System.ComponentModel.Component
{
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Name { get; set; }
public int Age { get; set; }
}
The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is not just a plain old object anymore.
You need to do the following:
Create a background with rounded corners for the Dialog's background:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#fff" />
<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
</shape>
Now in your Dialog's XML file in the root layout use that background with required margin:
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:background="@drawable/dialog_background"
finally in the java part you need to do this:
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(layoutResId);
View v = getWindow().getDecorView();
v.setBackgroundResource(android.R.color.transparent);
This works perfectly for me.
Use ThenBy
:
var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)
See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx
You might want to try the full login command:
mysql -h host -u root -p
where host would be 127.0.0.1
.
Do this just to make sure cooperation exists.
Using mysql -u root -p
allows me to do a a lot of database searching, but refuses any database creation due to a path setting.
Here is a list of almost all resolutions of tablets, with the most common ones in bold :
2560X1600
1366X768
1920X1200
1280X800
1280X768
1024X800
1024X768
1024X600
960X640
960X540
854X480
800X600
800X480
800X400
Happy designing .. ! :)
Please check if you have already close the database connection or not. In my case i was getting the error because the connection was close in upper line.
OpenCV Specific
Opencv supports filesystem, probably through its dependency Boost.
#include <opencv2/core/utils/filesystem.hpp>
cv::utils::fs::createDirectory(outputDir);
For example, a feature only works for api21 up the following we fix bugs in api21 down
if(Build.VERSION.SDK_INT >= 21) {
//only api 21 above
}else{
//only api 21 down
}
Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.
Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");
Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;
Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);
Your Java application now has a drop-down date selection dialog.
Actually, I see that ECMAScript (JavaScript) DOES INDEED have a goto statement. However, the JavaScript goto has two flavors!
The two JavaScript flavors of goto are called labeled continue and labeled break. There is no keyword "goto" in JavaScript. The goto is accomplished in JavaScript using the break and continue keywords.
And this is more or less explicitly stated on the w3schools website here http://www.w3schools.com/js/js_switch.asp.
I find the documentation of the labeled continue and labeled break somewhat awkwardly expressed.
The difference between the labeled continue and labeled break is where they may be used. The labeled continue can only be used inside a while loop. See w3schools for some more information.
===========
Another approach that will work is to have a giant while statement with a giant switch statement inside:
while (true)
{
switch (goto_variable)
{
case 1:
// some code
goto_variable = 2
break;
case 2:
goto_variable = 5 // case in etc. below
break;
case 3:
goto_variable = 1
break;
etc. ...
}
}
kth largest element means, we need to sort the array and then, count down from the end of array. For example
const array= [2, 32, 12, 3, 78, 99, 898, 8, 1] // we need to sort this
const sortedArray= [1, 2, 3, 8, 12, 32, 78, 99, 898]
5th largest element means from the end count down 5 elements which is 12.
By default most languages implement quick sort or merge sort because they are the most optimized sorts. I solve this problem with the quick sort. Quick sort sorts the array in place, it does not give us back a new array and like merge sort it is recursive. Downside of quick sort, in worst case scenario, its time complexity is O(n**2) "n square".
Quick sort is divide-and-conquer algorithm which is a problem is solved by solving all of its smaller components. We choose the last element as the pivot element (Some algorithms choose the first item as pivot, some choose the last item when it starts). Pivot element is the partitioning element. this is our array=[2, 32, 12, 3, 78, 99, 898, 8, 1]
we use 2 pointers, i,j starts from the first element. "i" keeps track of where is the final place of pivot.
i=j=2 //starting point
"j" is going to scan the array, and compare each element to the pivot. If "j" is smaller than pivot, we will swap "i" and "j" and move "i" and "j" forward. When "j" reaches pivot, we swap "i" with pivot. In our example pivot is 1
, 1 is the smaller number, "j" will reach the pivot=1
without swapping "i","j". Remember "i" is the placeholder for the pivot. So when "j" reaches pivot, 1 and 2 will be swapped.
The purpose of this operation to find all of elements that smaller than pivot to its left. Note that all the elements that are on the left of pivot is smaller than pivot, but left side is not sorted. Then we divide the array from the pivot into 2 sub arrays and recursively apply the quick sort.
const quickSort = function (array, left, right) {
// if left=right, it means we have only one item, it is already sorted
if (left < right) {
const partitionIndex = partition(array, left, right);
quickSort(array, left, partitionIndex - 1);
quickSort(array, partitionIndex + 1, right);
}
};
With using "i" and "j" pointers, this is how we find the partitioning index
const partition = function (array, left, right) {
const pivotElement = array[right];
let partitionIndex = left;
for (let j = left; j < right; j++) {
if (array[j] < pivotElement) {
swap(array, partitionIndex, j);
partitionIndex++;
}
}
// if none of the "j" values is smaller than pivot, when "j" reaches the pivot, we swap "i'th" element with pivot
swap(array, partitionIndex, right);
return partitionIndex;
};
this is a simple implementation of swap function:
const swap = function (array, i, j) {
const temp = array[i];
array[i] = array[j];
array[j] = temp;
};
Try it ..
UPDATE PRODUCTION a
SET (name, count) = (
SELECT name, count
FROM STAGING b
WHERE a.ID = b.ID)
WHERE EXISTS (SELECT 1
FROM STAGING b
WHERE a.ID=b.ID
);
If you are using terminal just type the following:
locate my.cnf
The AppHarbor gang has been struggling with this and has developed a temporary solution using SQL server management objects and SqlBulkCopy.
Check out their blog post about it, or go straight to the code.
They've only tested it with AppHarbor but it may be worth checking out.
Instead of using input type button
you can use button
and insert the image inside the button content.
<button class="btn btn-default">
<img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook
</button>
The problem with doing this only with CSS is that you cannot set linear-gradient
to the background you must use solid color.
.sign-in-facebook {
background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;
background-position: -9px -7px;
background-repeat: no-repeat;
background-size: 39px 43px;
padding-left: 41px;
color: #000;
}
.sign-in-facebook:hover {
background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;
background-position: -9px -7px;
background-repeat: no-repeat;
background-size: 39px 43px;
padding-left: 41px;
color: #000;
}
body {_x000D_
padding: 30px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style type="text/css">_x000D_
.sign-in-facebook {_x000D_
background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;_x000D_
background-position: -9px -7px;_x000D_
background-repeat: no-repeat;_x000D_
background-size: 39px 43px;_x000D_
padding-left: 41px;_x000D_
color: #000;_x000D_
}_x000D_
.sign-in-facebook:hover {_x000D_
background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;_x000D_
background-position: -9px -7px;_x000D_
background-repeat: no-repeat;_x000D_
background-size: 39px 43px;_x000D_
padding-left: 41px;_x000D_
color: #000;_x000D_
}_x000D_
</style>_x000D_
_x000D_
_x000D_
<h4>Only with CSS</h4>_x000D_
_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
_x000D_
<h4>Only with HTML</h4>_x000D_
_x000D_
<button class="btn btn-default">_x000D_
<img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook_x000D_
</button>
_x000D_
From a quick read of the previous answers, they look correct, but it doesn't look like anyone mentioned the new configuration facilities in Visual Studio 2008. It still uses app.config (copied at compile time to YourAppName.exe.config), but there is a UI widget to set properties and specify their types. Double-click Settings.settings in your project's "Properties" folder.
The best part is that accessing this property from code is typesafe - the compiler will catch obvious mistakes like mistyping the property name. For example, a property called MyConnectionString in app.config would be accessed like:
string s = Properties.Settings.Default.MyConnectionString;
I use scoop as command-liner installer for Windows... scoop rocks!
The quick answer (use PowerShell):
PS C:\Users\myuser> scoop install ruby
Longer answer:
Just searching for ruby:
PS C:\Users\myuser> scoop search ruby
'main' bucket:
jruby (9.2.7.0)
ruby (2.6.3-1)
'versions' bucket:
ruby19 (1.9.3-p551)
ruby24 (2.4.6-1)
ruby25 (2.5.5-1)
Check the installation info :
PS C:\Users\myuser> scoop info ruby
Name: ruby
Version: 2.6.3-1
Website: https://rubyinstaller.org
Manifest:
C:\Users\myuser\scoop\buckets\main\bucket\ruby.json
Installed: No
Environment: (simulated)
GEM_HOME=C:\Users\myuser\scoop\apps\ruby\current\gems
GEM_PATH=C:\Users\myuser\scoop\apps\ruby\current\gems
PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\bin
PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\gems\bin
Output from installation:
PS C:\Users\myuser> scoop install ruby
Updating Scoop...
Updating 'extras' bucket...
Installing 'ruby' (2.6.3-1) [64bit]
rubyinstaller-2.6.3-1-x64.7z (10.3 MB) [============================= ... ===========] 100%
Checking hash of rubyinstaller-2.6.3-1-x64.7z ... ok.
Extracting rubyinstaller-2.6.3-1-x64.7z ... done.
Linking ~\scoop\apps\ruby\current => ~\scoop\apps\ruby\2.6.3-1
Persisting gems
Running post-install script...
Fetching rake-12.3.3.gem
Successfully installed rake-12.3.3
Parsing documentation for rake-12.3.3
Installing ri documentation for rake-12.3.3
Done installing documentation for rake after 1 seconds
1 gem installed
'ruby' (2.6.3-1) was installed successfully!
Notes
-----
Install MSYS2 via 'scoop install msys2' and then run 'ridk install' to install the toolchain!
'ruby' suggests installing 'msys2'.
PS C:\Users\myuser>
if you need to select multiple columns from dataframe use 2 pairs of square brackets eg.
df[["product_id","customer_id","store_id"]]
Adding another answer to the bunch (no pun intended)...
You do need to call the doAnswer method if you can't\don't want to use spy's. However, you don't necessarily need to roll your own Answer. There are several default implementations. Notably, CallsRealMethods.
In practice, it looks something like this:
doAnswer(new CallsRealMethods()).when(mock)
.voidMethod(any(SomeParamClass.class));
Or:
doAnswer(Answers.CALLS_REAL_METHODS.get()).when(mock)
.voidMethod(any(SomeParamClass.class));
Change the body
element into a flex container
and the div
into a flex item
:
body {_x000D_
display: flex;_x000D_
height: 100vh;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
div {_x000D_
flex: 1;_x000D_
background: tan;_x000D_
}
_x000D_
<div></div>
_x000D_
If you're facing this issue with macOS Catalina, I recommend these steps:
Install Homebrew (if you haven't already done so): head over to brew.sh or simply run this command: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Run brew install [email protected]
Update your $PATH variable to include the newly installed version of php:
echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/usr/local/opt/[email protected]/sbin:$PATH"' >> ~/.zshrc
Reload your shell preferences script $ source ~/.zshrc
or source ~/.bashrc
Finally, install laravel: composer global require laravel/installer
Some times even I type Ctrl+Alt+L is not working in XML, so found this way to make it work.
Go to Settings --> Editor --> Code Style --> Select Default --> Ok.
For your reference see the screenshot:
We've done this with templates. You could do something like this:
// Specialization for 2-byte types.
template<>
inline void endian_byte_swapper< 2 >(char* dest, char const* src)
{
// Use bit manipulations instead of accessing individual bytes from memory, much faster.
ushort* p_dest = reinterpret_cast< ushort* >(dest);
ushort const* const p_src = reinterpret_cast< ushort const* >(src);
*p_dest = (*p_src >> 8) | (*p_src << 8);
}
// Specialization for 4-byte types.
template<>
inline void endian_byte_swapper< 4 >(char* dest, char const* src)
{
// Use bit manipulations instead of accessing individual bytes from memory, much faster.
uint* p_dest = reinterpret_cast< uint* >(dest);
uint const* const p_src = reinterpret_cast< uint const* >(src);
*p_dest = (*p_src >> 24) | ((*p_src & 0x00ff0000) >> 8) | ((*p_src & 0x0000ff00) << 8) | (*p_src << 24);
}
After you run MySQL Shell and you have seen following:
mysql-js>
Firstly, you should:
mysql-js>\sql
Secondly:
mysql-sql>\connect username@servername (root@localhost)
And finally:
Enter password:*********
If you are the only the person working on the project, what you can do is:
git checkout master
git push origin +HEAD
This will set the tip of origin/master to the same commit as master (and so delete the commits between 41651df and origin/master)
I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.
If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.
There is really no reason to dig through paths; the IDE hands it to you (at least with version 1.5.1).
In the Build
menu, select Build APK
:
A dialog will appear:
If you are using a newer version of Android Studio, it might look like this:
Clicking the Show in Explorer
or locate
link, you will be presented with a file explorer positioned somewhere near wherever Android Studio put the APK file:
But in AS 3, when you click locate
, it puts you at the app
level. You need to go into the release
folder to get your APK
file.
This question -- Why do Sublime Text 3 Themes not affect the sidebar? -- helped me out.
The steps I followed:
%AppData%\Sublime Text 3\Packages\User
)Default.sublime-theme
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
You will want to verify whatever your calling is valid. For example, in the case of a specific function, you will want to check and see if the function exists:
function doIt($callback) {
if(function_exists($callback)) {
$callback();
} else {
// some error handling
}
}
1. Without plugin
class IndiSampleState extends State<ProgHudPage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
),
body: Center(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(child: CircularProgressIndicator(),);
});
await loginAction();
Navigator.pop(context);
},
),
));
}
Future<bool> loginAction() async {
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
2. With plugin
check this plugin progress_hud
add the dependency in the pubspec.yaml file
dev_dependencies:
progress_hud:
import the package
import 'package:progress_hud/progress_hud.dart';
Sample code is given below to show and hide the indicator
class ProgHudPage extends StatefulWidget {
@override
_ProgHudPageState createState() => _ProgHudPageState();
}
class _ProgHudPageState extends State<ProgHudPage> {
ProgressHUD _progressHUD;
@override
void initState() {
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.white,
containerColor: Colors.blue,
borderRadius: 5.0,
loading: false,
text: 'Loading...',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('ProgressHUD Demo'),
),
body: new Stack(
children: <Widget>[
_progressHUD,
new Positioned(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async{
_progressHUD.state.show();
await loginAction();
_progressHUD.state.dismiss();
},
),
bottom: 30.0,
right: 10.0)
],
));
}
Future<bool> loginAction()async{
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
I think you can use Step 1: Select text Step 2: Ctrl + Shift + P Step 3: Enter Uppercae
@Amit's answer is good because it will work in both Mustache and Handlebars.
As far as Handlebars-only solutions, I've seen a few and I like the each_with_key
block helper at https://gist.github.com/1371586 the best.
'key'
, or 'property'
, etc.Iterate through the GridView rows and make the cells of your target columns invisible. In this example I want to keeps columns 4-6 visible as is, so we skip those:
foreach (GridViewRow row in yourGridView.Rows)
{
for (int i = 0; i < rows.Cells.Count; i++)
{
switch (i)
{
case 4:
case 5:
case 6:
continue;
}
row.Cells[i].Visible = false;
};
};
Then you will need to remove the column headers separately (keep in mind that removing header cells changes the length of the GridView after each removal):
grdReportRole.HeaderRow.Cells.RemoveAt(0);
Being specific about this keeps you away from the whole TRUE in VB is -1 and in other langauges true is just NON ZERO. Keeping the boolean field as true or false keeps java outside of this argument.
Networking code is notoriously difficult to write, test and debug.
You often have lots of things to consider such as:
what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.
are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive
how does congestion in the real world which causes delays in the stream affect your reading/writing logic
If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).
Here are several different ways to handle the exchange:
have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"
use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"
use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.
have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)
Each approach has its pros and cons for "correctness".
The code below uses the "timeout" method, as that seems to be the one you want.
See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream
on the TCPClient
so you can change the ReadTimeout
.
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
// Set a 250 millisecond timeout for reading (instead of Infinite the default)
stm.ReadTimeout = 250;
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
int bytesread = stm.Read(resp, 0, resp.Length);
while (bytesread > 0)
{
memStream.Write(resp, 0, bytesread);
bytesread = stm.Read(resp, 0, resp.Length);
}
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
As a footnote for other variations on this writing network code...when doing a Read
where you want to avoid a "block", you can check the DataAvailable
flag and then ONLY read what is in the buffer checking the .Length
property e.g. stm.Read(resp, 0, stm.Length);
Just to point onto the example posted by Mathew
public sealed class Singleton
{
// Because Singleton's constructor is private, we must explicitly
// give the Lazy<Singleton> a delegate for creating the Singleton.
private static readonly Lazy<Singleton> instanceHolder =
new Lazy<Singleton>(() => new Singleton());
private Singleton()
{
...
}
public static Singleton Instance
{
get { return instanceHolder.Value; }
}
}
before the Lazy was born we would have done it this way:
private static object lockingObject = new object();
public static LazySample InstanceCreation()
{
if(lazilyInitObject == null)
{
lock (lockingObject)
{
if(lazilyInitObject == null)
{
lazilyInitObject = new LazySample ();
}
}
}
return lazilyInitObject ;
}
var classname=$('#div1').attr('class')
As it was mentioned above CasperJS is the best tool to fill and send forms. Simplest possible example of how to fill & submit form using fill() function:
casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
this.fill('form#loginForm', {
'login': 'admin',
'password': '12345678'
}, true);
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
Take a look at these articles describing how LinkedIn and Digg are built:
There's also "Big Data: Viewpoints from the Facebook Data Team" that might be helpful:
Also, there's this article that talks about non-relational databases and how they're used by some companies:
http://www.readwriteweb.com/archives/is_the_relational_database_doomed.php
You'll see that these companies are dealing with data warehouses, partitioned databases, data caching and other higher level concepts than most of us never deal with on a daily basis. Or at least, maybe we don't know that we do.
There are a lot of links on the first two articles that should give you some more insight.
UPDATE 10/20/2014
Murat Demirbas wrote a summary on
http://muratbuffalo.blogspot.com/2014/10/facebooks-software-architecture.html
HTH