You can include a legend template in the chart options:
//legendTemplate takes a template as a string, you can populate the template with values from your dataset
var options = {
legendTemplate : '<ul>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<li>'
+'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'</li>'
+'<% } %>'
+'</ul>'
}
//don't forget to pass options in when creating new Chart
var lineChart = new Chart(element).Line(data, options);
//then you just need to generate the legend
var legend = lineChart.generateLegend();
//and append it to your page somewhere
$('#chart').append(legend);
You'll also need to add some basic css to get it looking ok.
Simply add these to your ggplot:
+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for
p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge'
could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.
This is not an error, it is a warning from your Microsoft compiler.
Select your project and click "Properties" in the context menu.
In the dialog, chose Configuration Properties
-> C/C++
-> Preprocessor
In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS
to turn those warnings off.
Blundell's first answer didn't work for me. However it showed me the right way. I have done the same thing like this:
> for i in `git ls-files -i --exclude-from=.gitignore`; do git rm --cached $i; done
> git commit -m 'Removed all files that are in the .gitignore'
> git push origin master
I advise you to check the files to be deleted first by running the below statement:
git ls-files -i --exclude-from=.gitignore
I was using a default .gitignore file for visual studio and I noticed that it was removing all log and bin folders in the project which was not my intended action.
Here's a way I am doing database restore from production to development:
NOTE: I am doing it via SSAS job to push production database to development daily:
Step1: Delete previous day backup in development:
declare @sql varchar(1024);
set @sql = 'DEL C:\ProdAEandAEXdataBACKUP\AE11.bak'
exec master..xp_cmdshell @sql
Step2: Copy production database to development:
declare @cmdstring varchar(1000)
set @cmdstring = 'copy \\Share\SQLDBBackup\AE11.bak C:\ProdAEandAEXdataBACKUP'
exec master..xp_cmdshell @cmdstring
Step3: Restore by running .sql script
SQLCMD -E -S dev-erpdata1 -b -i "C:\ProdAEandAEXdataBACKUP\AE11_Restore.sql"
Code that is within AE11_Restore.sql file:
RESTORE DATABASE AE11
FROM DISK = N'C:\ProdAEandAEXdataBACKUP\AE11.bak'
WITH MOVE 'AE11' TO 'E:\SQL_DATA\AE11.mdf',
MOVE 'AE11_log' TO 'D:\SQL_LOGS\AE11.ldf',
RECOVERY;
Alexander Abakumov's answer is the correct one. It solved every binding issue I had updating the underlying data and having the grid update.
Its easy to implement and modify any existing source code you have.
grdDetails.DataSource = new System.Windows.Forms.BindingSource { DataSource = OrderDetails };
In Python 3.
GPA = 2.5
print(" %6.1f " % GPA)
6.1f
means after the dots 1 digits show if you print 2 digits after the dots you should only %6.2f
such that %6.3f
3 digits print after the point.
Never mind, I found the answer.
This will do the trick.
Dim colIndex As Long
colIndex = Application.Match(colName, Range(Cells(rowIndex, 1), Cells(rowIndex, 100)), 0)
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
Windows imposes a memory limit per process, you can see what it is for each version here
See:
User-mode virtual address space for each 64-bit process;
With IMAGE_FILE_LARGE_ADDRESS_AWARE set (default):
x64: 8 TB
Intel IPF: 7 TB
2 GB with IMAGE_FILE_LARGE_ADDRESS_AWARE cleared
The javascript array has a constructor that accepts the length of the array:
let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]
However, this is just the initial size, there's no restriction on changing that:
arr.push(5);
console.log(arr); // [undefined × 3, 5]
Typescript has tuple types which let you define an array with a specific length and types:
let arr: [number, number, number];
arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'
Unless you're trying to upload the file using ajax, just submit the form to /upload/image
.
<form enctype="multipart/form-data" action="/upload/image" method="post">
<input id="image-file" type="file" />
</form>
If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:
From docs and example it is not clear that classpath manipulation is not allowed.
<configuration>
<compilerArgs>
<arg>classpath=${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)
-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.
Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?
<properties>
<cpfile>cp.txt</cpfile>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>build-classpath</id>
<phase>generate-sources</phase>
<goals>
<goal>build-classpath</goal>
</goals>
<configuration>
<outputFile>${cpfile}</outputFile>
</configuration>
</execution>
</executions>
</plugin>
Read file (Read a file into a Maven property)
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
def file = new File(project.properties.cpfile)
project.properties.cp = file.getText()
</source>
</configuration>
</execution>
</executions>
</plugin>
and finally
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<compilerArgs>
<arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
</plugin>
You can use numpy:
import numpy as np
Example from Empty Array:
np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]])
As far as I know there is not an easy way to do this since Javascript/JQuery does not have access to the local filesystem. There are some new features in html 5 that allows you to check certain meta data such as file size but I'm not sure if you can actually get the image dimensions.
Here is an article I found regarding the html 5 features, and a work around for IE that involves using an ActiveX control. http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html
There are several more things you might want to audit, such as table/column names, computer/application from which an update was made, and more.
Now, this depends on how detailed auditing you really need and at what level.
We started building our own trigger-based auditing solution, and we wanted to audit everything and also have a recovery option at hand. This turned out to be too complex, so we ended up reverse engineering the trigger-based, third-party tool ApexSQL Audit to create our own custom solution.
Tips:
Include before/after values
Include 3-4 columns for storing the primary key (in case it’s a composite key)
Store data outside the main database as already suggested by Robert
Spend a decent amount of time on preparing reports – especially those you might need for recovery
Plan for storing host/application name – this might come very useful for tracking suspicious activities
For this error:
~/Library/Python/2.7/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory`
The source of this problem is a bad python path hardcoded in pip (which means it won't be fixed by e.g. changing your $PATH). That path is no longer hardcoded in the lastest version of pip, so a solution which should work is:
pip install --upgrade pip
But of course, this command uses pip, so it fails with the same error.
The way to bootstrap yourself out of this mess:
which pip
#!/usr/local/opt/python/bin/python2.7
to e.g. #!/usr/local/opt/python2/bin/python2.7
(note the python2 in the path), or any path to a working python interpreter on your machine.pip install --upgrade pip
(this overwrites your hack and gets pip working at the latest version, where the interpreter issue should be fixed)For me, I found this issue by first having the identical issue from virtualenv:
~/Library/Python/2.7/bin/virtualenv: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory`
The solution here is to run
pip uninstall virtualenv
pip install virtualenv
If running that command gives the same error from pip, see above.
Here is a great simple dynamic breadcrumb (tweak as needed):
<?php
$docroot = "/zen/index5.php";
$path =($_SERVER['REQUEST_URI']);
$names = explode("/", $path);
$trimnames = array_slice($names, 1, -1);
$length = count($trimnames)-1;
$fixme = array(".php","-","myname");
$fixes = array(""," ","My<strong>Name</strong>");
echo '<div id="breadwrap"><ol id="breadcrumb">';
$url = "";
for ($i = 0; $i <= $length;$i++){
$url .= $trimnames[$i]."/";
if($i>0 && $i!=$length){
echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>';
}
elseif ($i == $length){
echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>';
}
else{
echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span> </span></a></li>';
}
}
echo '</ol>';
?>
"banana".count("ana")
returns 1 instead of 2 !
I think the method iterates over the string (or the list) with a step equal to the length of the substring so it doesn't see this kind of stuff.
So if you want a "full count" you have to implement your own counter with the correct loop of step 1
Correct me if I'm wrong...
“C:\Users\admin\Downloads\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf” is misleading, it’s not the file which sets the Java Home variable. The actually file used is”%AppData%\sqldeveloper{PRODUCT_VERSION}\product.conf” [in my case it is "%AppData%\sqldeveloper\1.0.0.0.0\product.conf"]
You can do it using xml as well:
<field name="acmeOne" type="string" column="acmeOne" length="36">
<options>
<option name="comment">Your SQL field comment goes here.</option>
<option name="default">Default Value</option>
</options>
</field>
In case someone stumbled upon this problem when working on Grails (or pure Spring) web application, here is the post that helped me:
http://forum.spring.io/forum/spring-projects/web/2491-solved-character-encoding-and-multipart-forms
To set default encoding to UTF-8 (instead of the ISO-8859-1) for multipart requests, I added the following code in resources.groovy (Spring DSL):
multipartResolver(ContentLengthAwareCommonsMultipartResolver) {
defaultEncoding = 'UTF-8'
}
The CosisEntities
class is your DbContext
. When you create a context in a using
block, you're defining the boundaries for your data-oriented operation.
In your code, you're trying to emit the result of a query from a method and then end the context within the method. The operation you pass the result to then tries to access the entities in order to populate the grid view. Somewhere in the process of binding to the grid, a lazy-loaded property is being accessed and Entity Framework is trying to perform a lookup to obtain the values. It fails, because the associated context has already ended.
You have two problems:
You're lazy-loading entities when you bind to the grid. This means that you're doing lots of separate query operations to SQL Server, which are going to slow everything down. You can fix this issue by either making the related properties eager-loaded by default, or asking Entity Framework to include them in the results of this query by using the Include
extension method.
You're ending your context prematurely: a DbContext
should be available throughout the unit of work being performed, only disposing it when you're done with the work at hand. In the case of ASP.NET, a unit of work is typically the HTTP request being handled.
Aside from the long list of remove commands in your question, which seems quite comprehensive in my recent experience of exactly this issue, I found mysql.sock running in /private/var and removed that. I used
find / -name mysql -print 2> /dev/null
...to find anything that looked like a mysql directory or file and removed most of what came up (aside from Perl/Python access modules). You may also need to check that the daemon is not still running using Activity Monitor (or at the command line using ps -A
). I found that mysqld was still running even after deleting the files.
Using the -X
flag with whatever HTTP verb you want:
curl -X PUT -d arg=val -d arg2=val2 localhost:8080
This example also uses the -d
flag to provide arguments with your PUT request.
This works on the Spring Tool Suite v 3.1.0.RELEASE, but I'm guessing it's also available on Eclipse as well.
After deleting the artifacts by hand (as stated by palacsint above) in the /username/.m2
directory, re-index the files by doing the following:
Go to:
Windows->Preferences->Maven->User Settings
menu.Click the Reindex
button next to the Local Repository
text box. Click "Apply" then "OK" and you're done.
This is an old thread, but as it still gets viewed and recently active "26" days ago as of this post, here is a quick solution.
There is no .env file initially, you must duplicate .env.example as .env.
In windows, you can open a command prompt aka the CLI and paste the exact code below while inside the root directory of the project. Must include the ( at the start line without space.
(
echo APP_NAME=Laravel
echo APP_ENV=local
echo APP_KEY=
echo APP_DEBUG=true
echo APP_URL=http://localhost
echo.
echo LOG_CHANNEL=stack
echo.
echo DB_CONNECTION=mysql
echo DB_HOST=127.0.0.1
echo DB_PORT=3306
echo DB_DATABASE=homestead
echo DB_USERNAME=homestead
echo DB_PASSWORD=secret
echo.
echo BROADCAST_DRIVER=log
echo CACHE_DRIVER=file
echo SESSION_DRIVER=file
echo SESSION_LIFETIME=120
echo QUEUE_DRIVER=sync
echo.
echo REDIS_HOST=127.0.0.1
echo REDIS_PASSWORD=null
echo REDIS_PORT=6379
echo.
echo MAIL_DRIVER=smtp
echo MAIL_HOST=smtp.mailtrap.io
echo MAIL_PORT=2525
echo MAIL_USERNAME=null
echo MAIL_PASSWORD=null
echo MAIL_ENCRYPTION=null
echo.
echo PUSHER_APP_ID=
echo PUSHER_APP_KEY=
echo PUSHER_APP_SECRET=
echo PUSHER_APP_CLUSTER=mt1
echo.
echo MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
echo MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
)>".env"
Just press enter to exit the prompt and you should have the .env
file with the default settings created in the same directory you typed above CLI
command.
Hope this helps.
As far as I know that only works in Internet Explorer.
See also Dynamic Tools - JavaScript Copy To Clipboard, but it requires the user to change the configuration first and even then it doesn't seems to work.
Have a look at this sample:
public class A {
//statements
}
public class B extends A {
public void foo() { }
}
A a=new B();
//To execute **foo()** method.
((B)a).foo();
The reason for "permission denied" is because your Android machine has not been correctly rooted. Did you see $
after you started adb shell
? If you correctly rooted your machine, you would have seen #
instead.
If you see the $
, try entering Super User mode by typing su
. If Root is enabled, you will see the #
- without asking for password.
Instead Animals == "bird*"
Animals = "bird*"
should work.
I had a similar issue with the iteration and I landed here. Maybe someone else is also doing the same mistake I did.
In my case, the selector was not the problem at all. The problem was that I had messed up the javascript code:
I had a loop and a subloop. The subloop was also using i
as a counter, instead of j
, so because the subloop was overriding the value of i
of the main loop, this one never got to the second iteration.
var dayContainers = document.getElementsByClassName('day-container');
for(var i = 0; i < dayContainers.length; i++) { //loop of length = 2
var thisDayDiv = dayContainers[i];
// do whatever
var inputs = thisDayDiv.getElementsByTagName('input');
for(var j = 0; j < inputs.length; j++) { //loop of length = 4
var thisInput = inputs[j];
// do whatever
};
};
let calendar = Calendar.current
let hours = calendar.component(.hour, from: Date())
let minutes = calendar.component(.minute, from: Date())
let seconds = calendar.component(.second, from: Date())
You can create a thread just like this:
Thread thread = new Thread(new Runnable() {
public void run() {
}
});
thread.start();
Also, you can use Runnable, Asyntask, Timer, TimerTaks and AlarmManager to excecute Threads.
If you are using rails > 3 version, then there is a concept called asset pipeline
. You could add your CSS to
app/assets/stylesheets
then it will automatically be picked up by the app. (this is useful as rails will automatically compress the CSS files)
read more here about the asset pipeline
according to the mySQL reference manual this the syntax of using if and else statement :
IF search_condition THEN statement_list [ELSEIF search_condition THEN statement_list] ... [ELSE statement_list] END IF
So regarding your query :
x = IF((action=2)&&(state=0),1,2);
or you can use
IF ((action=2)&&(state=0)) then
state = 1;
ELSE
state = 2;
END IF;
There is good example in this link : http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/
NOTE: As of July 2020, text-overflow: ellipsis
works for <select>
on Chrome
HTML is limited in what it specifies for form controls. That leaves room for operating system and browser makers to do what they think is appropriate on that platform (like the iPhone’s modal select
which, when open, looks totally different from the traditional pop-up menu).
If it bugs you, you can use a customizable replacement, like Chosen, which looks distinct from the native select
.
Or, file a bug against a major operating system or browser. For all we know, the way text is cut off in select
s might be the result of a years-old oversight that everyone copied, and it might be time for a change.
You can do that in your app.config. like that:
maxReceivedMessageSize="2147483647"
(The max value is Int32.MaxValue
)
Or in Code:
WSHttpBinding binding = new WSHttpBinding();
binding.Name = "MyBinding";
binding.MaxReceivedMessageSize = Int32.MaxValue;
Note:
If your service is open to the Wide world, think about security when you increase this value.
If you do truly want the IP assigned to your emulator:
adb shell
ifconfig eth0
Which will give you something like:
eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]
You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:
-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
k NUMBER:= 0;
BEGIN
FOR i IN 1..10 LOOP
k:= k+1;
dbms_output.put_line(i||' '||k);
END LOOP;
END;
/
-- Cursor FOR loop --
set serveroutput on
DECLARE
CURSOR c1 IS SELECT * FROM scott.emp;
i NUMBER:= 0;
BEGIN
FOR e_rec IN c1 LOOP
i:= i+1;
dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
END LOOP;
END;
/
-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
FROM dual
CONNECT BY LEVEL <= 10
/
you also should specify def name in the project settings here:
Configuration > Properties/Input/Advanced/Module > Definition File
One equivalent of lsof could be combined output from Sysinternals' handle and listdlls, i.e.:
c:\SysInternals>handle
[...]
------------------------------------------------------------------------------
gvim.exe pid: 5380 FOO\alois.mahdal
10: File (RW-) C:\Windows
1C: File (RW-) D:\some\locked\path\OpenFile.txt
[...]
c:\SysInternals>listdlls
[...]
------------------------------------------------------------------------------
Listdlls.exe pid: 6840
Command line: listdlls
Base Size Version Path
0x00400000 0x29000 2.25.0000.0000 D:\opt\SysinternalsSuite\Listdlls.exe
0x76ed0000 0x180000 6.01.7601.17725 C:\Windows\SysWOW64\ntdll.dll
[...]
c:\SysInternals>listdlls
Unfortunately, you have to "run as Administrator" to be able to use them.
Also listdlls and handle do not produce continuous table-like form so filtering filename would hide PID. findstr /c:pid: /c:<filename>
should get you very close with both utilities, though
c:\SysinternalsSuite>handle | findstr /c:pid: /c:Driver.pm
System pid: 4 \<unable to open process>
smss.exe pid: 308 NT AUTHORITY\SYSTEM
avgrsa.exe pid: 384 NT AUTHORITY\SYSTEM
[...]
cmd.exe pid: 7140 FOO\alois.mahdal
conhost.exe pid: 1212 FOO\alois.mahdal
gvim.exe pid: 3408 FOO\alois.mahdal
188: File (RW-) D:\some\locked\path\OpenFile.txt
taskmgr.exe pid: 6016 FOO\alois.mahdal
[...]
Here we can see that gvim.exe is the one having this file open.
Solution for change TextView
width to wrap content.
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.requestLayout();
// Call requestLayout() for redraw your TextView when your TextView is already drawn (laid out) (eg: you update TextView width when click a Button).
// If your TextView is drawing you may not need requestLayout() (eg: you change TextView width inside onCreate()). However if you call it, it still working well => for easy: always use requestLayout()
// Another useful example
// textView.getLayoutParams().width = 200; // For change `TextView` width to 200 pixel
Use ternary operator:
echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis
But in this case you can't use shorter reversed version because it will return bool(true)
in first condition.
echo (($test != '') ?: $redText); //this will not work properly for this case
This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.
So, which XML parsing module to pick?
Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.
Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.
Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692
I am using Xcode Version 11.4
In the attribute inspector, you can define the corner radius.
It won't show in the Storyboard but it will work fine when you run the project.
There is actually a reason behind why all these are messed up. A little more digging deeper is done in this thread and might be helpful to understand the reason why "\\" behaves like this.
What you can do and what you should do are different matters.
If the list is very short, or you are only ever going to call find once then use the linear approach above.
However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.
I also had the same issue. I've fixed it by using the following code.
<Button Width="30" Margin="0,5" HorizontalAlignment="Stretch" Click="OnSearch" >
<DockPanel>
<Image Source="../Resources/Back.jpg"/>
</DockPanel>
</Button>
Note: Make sure the build action of the image in the property window, should be Resource
.
I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement
.
A couple years late, but here is a solution that retrieves both inline styling and external styling:
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
Pass a jQuery object into css()
and it will return an object, which you can then plug back into jQuery's $().css()
, ex:
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
:)
Override the functions setUpdatedAt()
and getUpdatedAtColumn()
in your model
public function setUpdatedAt($value)
{
//Do-nothing
}
public function getUpdatedAtColumn()
{
//Do-nothing
}
What about replace the item if you know the position:
aList[0]=2014
Or if you don't know the position loop in the list, find the item and then replace it
aList = [123, 'xyz', 'zara', 'abc']
for i,item in enumerate(aList):
if item==123:
aList[i]=2014
break
print aList
To insert contents of the named file:
<!--#include virtual="filename.htm"-->
try using CHARLIST as shown below:
select distinct name from artists where name RLIKE '^[abc]';
use distinct only if you want distinct values only. To read about it Click here.
The approach I used when faced with this problem was to add the signer of the temporary certificate to the trusted authorities list on the computer in question.
I normally do testing with certificates created with CACERT, and adding them to my trusted authorities list worked swimmingly.
Doing it this way means you don't have to add any custom code to your application and it properly simulates what will happen when your application is deployed. As such, I think this is a superior solution to turning off the check programmatically.
$("head").append("<link>");
var css = $("head").children(":last");
css.attr({
rel: "stylesheet",
type: "text/css",
href: "address_of_your_css"
});
To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.
This means that if you generate a 200x200
image for xhdpi
devices, you should generate the same resource in 150x150
for hdpi
, 100x100
for mdpi
, and 75x75
for ldpi
devices.
Then, place the files in the appropriate drawable resource directory:
MyProject/
res/
drawable-xhdpi/
awesomeimage.png
drawable-hdpi/
awesomeimage.png
drawable-mdpi/
awesomeimage.png
drawable-ldpi/
awesomeimage.png
Any time you reference @drawable/awesomeimage
, the system selects the appropriate bitmap based on the screen's density.
There are a couple of things that you need to check related to this.
Whenever there is an error like this thrown related to making a secure connection, try running a script like the one below in Powershell with the name of the machine or the uri (like "www.google.com") to get results back for each of the different protocol types:
function Test-SocketSslProtocols {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][string]$ComputerName,
[int]$Port = 443,
[string[]]$ProtocolNames = $null
)
#set results list
$ProtocolStatusObjArr = [System.Collections.ArrayList]@()
if($ProtocolNames -eq $null){
#if parameter $ProtocolNames empty get system list
$ProtocolNames = [System.Security.Authentication.SslProtocols] | Get-Member -Static -MemberType Property | Where-Object { $_.Name -notin @("Default", "None") } | ForEach-Object { $_.Name }
}
foreach($ProtocolName in $ProtocolNames){
#create and connect socket
#use default port 443 unless defined otherwise
#if the port specified is not listening it will throw in error
#ensure listening port is a tls exposed port
$Socket = New-Object System.Net.Sockets.Socket([System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
$Socket.Connect($ComputerName, $Port)
#initialize default obj
$ProtocolStatusObj = [PSCustomObject]@{
Computer = $ComputerName
Port = $Port
ProtocolName = $ProtocolName
IsActive = $false
KeySize = $null
SignatureAlgorithm = $null
Certificate = $null
}
try {
#create netstream
$NetStream = New-Object System.Net.Sockets.NetworkStream($Socket, $true)
#wrap stream in security sslstream
$SslStream = New-Object System.Net.Security.SslStream($NetStream, $true)
$SslStream.AuthenticateAsClient($ComputerName, $null, $ProtocolName, $false)
$RemoteCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]$SslStream.RemoteCertificate
$ProtocolStatusObj.IsActive = $true
$ProtocolStatusObj.KeySize = $RemoteCertificate.PublicKey.Key.KeySize
$ProtocolStatusObj.SignatureAlgorithm = $RemoteCertificate.SignatureAlgorithm.FriendlyName
$ProtocolStatusObj.Certificate = $RemoteCertificate
}
catch {
$ProtocolStatusObj.IsActive = $false
Write-Error "Failure to connect to machine $ComputerName using protocol: $ProtocolName."
Write-Error $_
}
finally {
$SslStream.Close()
}
[void]$ProtocolStatusObjArr.Add($ProtocolStatusObj)
}
Write-Output $ProtocolStatusObjArr
}
Test-SocketSslProtocols -ComputerName "www.google.com"
It will try to establish socket connections and return complete objects for each attempt and successful connection.
After seeing what returns, check your computer registry via regedit (put "regedit" in run or look up "Registry Editor"), place
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL
in the filepath and ensure that you have the appropriate TLS Protocol enabled for whatever server you're trying to connect to (from the results you had returned from the scripts). Adjust as necessary and then reset your computer (this is required). Try connecting with the powershell script again and see what results you get back. If still unsuccessful, ensure that the algorithms, hashes, and ciphers that need to be enabled are narrowing down what needs to be enabled (IISCrypto is a good application for this and is available for free. It will give you a real time view of what is enabled or disabled in your SChannel registry where all these things are located).
Also keep in mind the Windows version, DotNet version, and updates you have currently installed because despite a lot of TLS options being enabled by default in Windows 10, previous versions required patches to enable the option.
One last thing: TLS is a TWO-WAY street (keep this in mind) with the idea being that the server's having things available is just as important as the client. If the server only offers to connect via TLS 1.2 using certain algorithms then no client will be able to connect with anything else. Also, if the client won't connect with anything else other than a certain protocol or ciphersuite the connection won't work. Browsers are also something that need to be taken into account with this because of their forcing errors on HTTP2 for anything done with less than TLS 1.2 DESPITE there NOT actually being an error (they throw it to try and get people to upgrade but the registry settings do exist to modify this behavior).
Any - boolean function that returns true when any of object in list satisfies condition set in function parameters. For example:
List<string> strings = LoadList();
boolean hasNonEmptyObject = strings.Any(s=>string.IsNullOrEmpty(s));
Where - function that returns list with all objects in list that satisfy condition set in function parameters. For example:
IEnumerable<string> nonEmptyStrings = strings.Where(s=> !string.IsNullOrEmpty(s));
Exists - basically the same as any but it's not generic - it's defined in List class, while Any is defined on IEnumerable interface.
I would suggest you take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.
Here is an example of loading jquery:
Modernizr.load([
{
load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
complete: function () {
if ( !window.jQuery ) {
Modernizr.load('js/libs/jquery-1.6.1.min.js');
}
}
},
{
// This will wait for the fallback to load and
// execute if it needs to.
load: 'needs-jQuery.js'
}
]);
I make my own extended class to see what I need, so when I need into my controller or my View, I only add the using to my namespace something like this:
public static class UserExtended
{
public static string GetFullName(this IPrincipal user)
{
var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.Name);
return claim == null ? null : claim.Value;
}
public static string GetAddress(this IPrincipal user)
{
var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.StreetAddress);
return claim == null ? null : claim.Value;
}
public ....
{
.....
}
}
In my controller:
using XXX.CodeHelpers.Extended;
var claimAddress = User.GetAddress();
In my razor:
@using DinexWebSeller.CodeHelpers.Extended;
@User.GetFullName()
The command line utility nmap can do this too:
nmap -sP 192.168.1.*
Bootstrap 3 removed those color options for badges. However, we can add those styles manually. Here's my solution, and here is the JS Bin:
.badge {
padding: 1px 9px 2px;
font-size: 12.025px;
font-weight: bold;
white-space: nowrap;
color: #ffffff;
background-color: #999999;
-webkit-border-radius: 9px;
-moz-border-radius: 9px;
border-radius: 9px;
}
.badge:hover {
color: #ffffff;
text-decoration: none;
cursor: pointer;
}
.badge-error {
background-color: #b94a48;
}
.badge-error:hover {
background-color: #953b39;
}
.badge-warning {
background-color: #f89406;
}
.badge-warning:hover {
background-color: #c67605;
}
.badge-success {
background-color: #468847;
}
.badge-success:hover {
background-color: #356635;
}
.badge-info {
background-color: #3a87ad;
}
.badge-info:hover {
background-color: #2d6987;
}
.badge-inverse {
background-color: #333333;
}
.badge-inverse:hover {
background-color: #1a1a1a;
}
DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'
IF PATINDEX('%[0-9]%', @str) > 0
PRINT 'YES, The string has numbers'
ELSE
PRINT 'NO, The string does not have numbers'
See man git-add
:
-f, --force
Allow adding otherwise ignored files.
So run this
git add --force my/ignore/file.foo
these are the commands:
git fetch origin
git merge origin/somebranch somebranch
if you do this on the second line:
git merge origin somebranch
it will try to merge the local master into your current branch.
The question, as I've understood it, was you fetched already locally and want to now merge your branch to the latest of the same branch.
It indeed may be useful for some debug or demonstration needs.
I found that Bob Copeland solution http://bobcopeland.com/blog/2012/10/goto-in-bash/ elegant:
#!/bin/bash
# include this boilerplate
function jumpto
{
label=$1
cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
eval "$cmd"
exit
}
start=${1:-"start"}
jumpto $start
start:
# your script goes here...
x=100
jumpto foo
mid:
x=101
echo "This is not printed!"
foo:
x=${x:-10}
echo x is $x
results in:
$ ./test.sh
x is 100
$ ./test.sh foo
x is 10
$ ./test.sh mid
This is not printed!
x is 101
First, Hungarian Notation is the practice of using a prefix to display a parameter's data type or intended use. Microsoft's naming conventions for says no to Hungarian Notation http://en.wikipedia.org/wiki/Hungarian_notation http://msdn.microsoft.com/en-us/library/ms229045.aspx
Using UPPERCASE is not encouraged as stated here: Pascal Case is the acceptable convention and SCREAMING CAPS. http://en.wikibooks.org/wiki/C_Sharp_Programming/Naming
Microsoft also states here that UPPERCASE can be used if it is done to match the the existed scheme. http://msdn.microsoft.com/en-us/library/x2dbyw72.aspx
This pretty much sums it up.
To compare entire revisions, it's simply:
svn diff -r 8979:11390
If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:
svn diff -r PREV:HEAD
(Note, without anything specified afterwards, all files in the specified revisions are compared.)
You can compare a specific file if you add the file path afterwards:
svn diff -r 8979:HEAD /path/to/my/file.php
You can also use file_put_contents()
:
file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);
interface:
defines the contract for a class which implements it
@interface:
defines the contract for an annotation
You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.
You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig
. It will give out some information and your local IP should look like 192.168.1.x.
I keep a current count and compare it to a total count. If the current count is less than the total count, I display the comma.
May not work if you don't have a total count prior to executing the JSON generation.
Then again, if your using PHP 5.2.0 or better, you can just format your response using the JSON API built in.
Try using:
git checkout branchName -- fileName
Ex:
git checkout master -- index.php
I know this is already answered, but because you said, this isn't exactly what you are looking for, I would like to point out the following alternative:
You can also use a configuration class instead of the properties or xml file.
-Dlog4j.configuratorClass=com.foo.BarConfigurator
See http://logging.apache.org/log4j/1.2/manual.html for details.
It should be something like...
<xsl:if test="contains($hhref, '1234')">
(not tested)
See w3schools (always a good reference BTW)
I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.
What I had to do was to install lombok
in the eclipse installation directory.
Download the lombok.jar
from here and then install it using the following command:
java -jar lombok.jar
After that make sure that the lombok.jar
is added in your build path. But make sure you don't add it twice by adding once through maven
or gradle
and once again in eclipse path.
After that clean
and build
the project again and see all the errors go away.
you can apply css an an object. So you can define your object in your javascript like this:
var my_css_class = { backgroundColor : 'blue', color : '#fff' };
And then simply apply it to all the elements you want
$("#myelement").css(my_css_class);
So it is reusable. What purpose would you do this for though?
I've seen all voted answers show how to set the summary with the exact current value, but the OP wanted also something like:
"Clean up messages after x days"* <- summary where x is the current Preference value
Here is my answer for achieving that
As per the documentation on ListPreference.getSummary()
:
Returns the summary of this ListPreference. If the summary has a String formatting marker in it (i.e. "%s" or "%1$s"), then the current entry value will be substituted in its place.
However, I tried this on several devices and it doesn't seem to work. With some research, I found a good solution in this answer. It simply consists of extending every Preference
you use and override getSummary()
to work as specified by Android documentation.
I had kafka running as a Docker container and similar messages were flooding to the log.
And KAFKA_ADVERTISED_HOST_NAME
was set to 'kafka'.
In my case the reason for error was the missing /etc/hosts
record for 'kafka' in 'kafka' container itself.
So, for example, running ping kafka
inside 'kafka' container would fail with ping: bad address 'kafka'
In terms of Docker this problem gets solved by specifying hostname
for the container.
Options to achieve it:
(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).
There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.
For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).
$ create table foo (bar int);
CREATE TABLE
$ select avg(bar) from foo;
avg
-----
(1 row)
$ select coalesce(avg(bar), 0) from foo;
coalesce
----------
0
(1 row)
$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
coalesce
--------------------
6.0000000000000000
(1 row)
of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"
Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.
$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
coalesce
--------------------
4.0000000000000000
(1 row)
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.
I'd recommend pygit2 - it uses the excellent libgit2 bindings
You can use ave
:
df$count <- ave(df$num, df[,c("name","type")], FUN=length)
I fixed this problem.The device system version is older then the sdk minSdkVersion? I just modified the minSdkVersion from android_L to 19 to target my nexus 4.4.4.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.12.2'
}
}
apply plugin: 'com.android.application'
repositories {
jcenter()
}
android {
**compileSdkVersion 'android-L'** modified to 19
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.antwei.uiframework.ui"
minSdkVersion 14
targetSdkVersion 'L'
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
**compile 'com.android.support:support-v4:21.+'** modified to compile 'com.android.support:support-v4:20.0.0'
}
how to modified the value by ide. select file->Project Structure -> Facets -> android-gradle and then modified the compile Sdk Version from android_L to 19
sorry I don't have enough reputation to add pictures
Checkout zirafa/bootstrap-grid-only. It contains only the bootstrap grid and responsive utilities that you need (no reset or anything), and simplifies the complexity of working directly with the LESS files.
use:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
You could create a helper function:
def re_match_group(pattern, str, out_groups):
del out_groups[:]
result = re.match(pattern, str)
if result:
out_groups[:len(result.groups())] = result.groups()
return result
And then use it like this:
groups = []
if re_match_group("I love (\w+)", statement, groups):
print "He loves", groups[0]
elif re_match_group("Ich liebe (\w+)", statement, groups):
print "Er liebt", groups[0]
elif re_match_group("Je t'aime (\w+)", statement, groups):
print "Il aime", groups[0]
It's a little clunky, but it gets the job done.
to list only commits details for specific file changes,
git log --follow file_1.rb
to list difference among various commits for same file,
git log -p file_1.rb
to list only commit and its message,
git log --follow --oneline file_1.rb
here's another one:
Drawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
You are dropping it, then creating it, then trying to create it again by using SELECT INTO
. Change to:
DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))
INSERT INTO #TMPGUARDIAN
SELECT LAST_NAME,FRST_NAME
FROM TBL_PEOPLE
In MS SQL Server you can create a table without a CREATE TABLE
statement by using SELECT INTO
If you use the Angular CLI to create your components, let's say CarComponent
, it attaches app
to the selector name (i.e app-car
) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car>
or change the selector in the CarComponent
to selector: 'car'
numpy.ndarray()
is a class, while numpy.array()
is a method / function to create ndarray
.
In numpy docs if you want to create an array from ndarray
class you can do it with 2 ways as quoted:
1- using array()
, zeros()
or empty()
methods:
Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)
) for instantiating an array.
2- from ndarray
class directly:
There are two modes of creating an array using __new__
:
If buffer is None, then only shape, dtype, and order are used.
If buffer is an object exposing the buffer interface, then all keywords are interpreted.
The example below gives a random array because we didn't assign buffer value:
np.ndarray(shape=(2,2), dtype=float, order='F', buffer=None) array([[ -1.13698227e+002, 4.25087011e-303], [ 2.88528414e-306, 3.27025015e-309]]) #random
another example is to assign array object to the buffer example:
>>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3])
from above example we notice that we can't assign a list to "buffer" and we had to use numpy.array() to return ndarray object for the buffer
Conclusion: use numpy.array()
if you want to make a numpy.ndarray()
object"
You can do it by listening to phone call events . You do it by having a BroadcastReceiver to PHONE_STATE and to NEW_OUTGOING_CALL. You find there what is the phone number.
Then when you decide to end the call, this is a bit tricky, because only from Android P it's guaranteed to work. Check here.
You want:
grep -A 5 '19:55' file
From man grep
:
Context Line Control
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a gup separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a group separator
(described under --group-separator) between contiguous groups of matches.
With the -o or --only-matching option, this has no effect and a warning
is given.
--group-separator=SEP
Use SEP as a group separator. By default SEP is double hyphen (--).
--no-group-separator
Use empty string as a group separator.
I think your document must be having enough space in the window to display its contents. That means there is no need to scroll down to see any more part of the document. In that case, document height would be equal to the window height.
It has already been mentioned that hashmaps are O(n/m)
in average, if n
is the number of items and m
is the size. It has also been mentioned that in principle the whole thing could collapse into a singly linked list with O(n)
query time. (This all assumes that calculating the hash is constant time).
However what isn't often mentioned is, that with probability at least 1-1/n
(so for 1000 items that's a 99.9% chance) the largest bucket won't be filled more than O(logn)
! Hence matching the average complexity of binary search trees. (And the constant is good, a tighter bound is (log n)*(m/n) + O(1)
).
All that's required for this theoretical bound is that you use a reasonably good hash function (see Wikipedia: Universal Hashing. It can be as simple as a*x>>m
). And of course that the person giving you the values to hash doesn't know how you have chosen your random constants.
TL;DR: With Very High Probability the worst case get/put complexity of a hashmap is O(logn)
.
There are some guys at Mozilla working on implementing a PDF reader using HTML5 and JavaScript. It is called pdf.js and one of the developers just made an interesting blog post about the project.
Setting window full height for empty divs
1st solution with absolute positioning - FIDDLE
.div1 {
position: absolute;
top: 0;
bottom: 0;
width: 25%;
}
.div2 {
position: absolute;
top: 0;
left: 25%;
bottom: 0;
width: 75%;
}
2nd solution with static (also can be used a relative) positioning & jQuery - FIDDLE
.div1 {
float: left;
width: 25%;
}
.div2 {
float: left;
width: 75%;
}
$(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
$(window).resize(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
});
});
Try this
'''
This is a multiline
comment. I can type here whatever I want.
'''
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
You could add the default rule with the alter table,
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()
then immediately set to null all the current existing rows:
UPDATE mytable SET created_at = NULL
Then from this point on the DEFAULT
will take effect.
In Java, you can escape quotes with \
:
String value = " \"ROM\" ";
I had the problem whereby VB6 IDE would not load the common controls (Sp6)with VB6 install on W7 64bit, specifically comctrl and msmask. I tried all the solutions proposed using regsrv32 (elevated), edited the registry, changing the version number in the vbp etc as proposed by MS and others. All failed. These solutions worked on my other 2 PCS but not this one. Eventually I removed IE11 and all worked properly afterwards. IE10 had never bene installed on thsi PC - we went straight from IE8 to IE11 and have been forced to backtrack to using IE8.
I have to say the simple solution above does not address the problem which is that the VB6 IDE will not load the common controls (using the Components menu selection under Project) - you get an error saying Object not loaded. So this will happen (and I proved this to myself) on any project, new or old that try to use theose common controls that will not load.
So my suggestion to anyone who has this problem is to try the manual register solution using regsrv32 route, then the edit the vbp to change the version, and if these fail uninstall IE11 (and defintely IE10). But this may still not be a 100% solution because if your existing project files ".vbp" contain references to the wrong common controls you need to correct that manually - this is where loading a new project, loading the Components you need inside the IDE, then edit the newly create vbp using notepad and copy the version numbers for the common controls to your existing vbp files.
New XCode 7 will only require 'UIFileSharingEnabled' key in Info.plist. 'CFBundleDisplayName' is not required any more.
One more hint: do not only modify the Info.plist of the 'tests' target. The main app and the 'tests' have different Info.plist.
How about Freebase? I think they have an API available, too.
You could create a mutable wrapper of the primitive int and create a Set of those:
class MutableInteger
{
private int value;
public int getValue()
{
return value;
}
public void setValue(int value)
{
this.value = value;
}
}
class Test
{
public static void main(String[] args)
{
Set<MutableInteger> mySet = new HashSet<MutableInteger>();
// populate the set
// ....
for (MutableInteger integer: mySet)
{
integer.setValue(integer.getValue() + 1);
}
}
}
Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.
<button onclick="history.go(-1);">Back </button>
The only way I know of doing it is by omitting the parameter. The only way to omit the parameter is to rearrange the parameter list so that the one you want to omit is after the parameters that you HAVE to set. For example:
function foo($blah, $y = "some other value", $x = "some value")
Then you can call foo like:
foo("blah", "test");
This will result in:
$blah = "blah";
$y = "test";
$x = "some value";
cursor.execute(sql,array)
Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)
In order to use Http in your app you will need to add the HttpModule to your app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
...
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
]
EDIT
As mentioned in the comment below, HttpModule
is deprecated
now, use import { HttpClientModule } from '@angular/common/http'
; Make sure HttpClientModule
in your imports:[]
array
You could use
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.
as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:
REPLACE:
((^.*$)(\n))(?=\k<1>)
by
$3
This will convert:
Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
to:
Shorts
Shorts Two Pack
Signature Braces
Signature Cotton Trousers
That's how I did it because I specifically needed those lines.
I had this problem and fixed it with manuel-84's suggestion. Using a 400x400px image worked great, while my smaller image never showed up in the sharer.
Note that Facebook recommends a minimum 200px square image as the og:image tag: https://developers.facebook.com/docs/opengraph/howtos/maximizing-distribution-media-content/#tags
Another approach is to use android.intent.action.USER_PRESENT
instead of android.intent.action.BOOT_COMPLETED
to avoid slow downs during the boot process. But this is only true
if the user has enabled the lock Screen - otherwise this intent is never broadcasted.
Reference blog - The Problem With Android’s ACTION_USER_PRESENT Intent
Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.
You should do this with any object that implements AutoClosable.
try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
String sqlToExecute = "SELECT * FROM persons";
try (ResultSet resultSet = statement.execute(sqlToExecute)) {
if (resultSet.next()) {
System.out.println(resultSet.getString("name");
}
}
} catch (SQLException e) {
System.out.println("Failed to select persons.");
}
The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.
You can use:
string regExp = "\\W";
This is equivalent to Daniel's "[^a-zA-Z0-9]
"
\W matches any nonword character. Equivalent to the Unicode categories [^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]
.
Create a new 640x480 image and fill it with purple (red+blue):
cv::Mat mat(480, 640, CV_8UC3, cv::Scalar(255,0,255));
Note:
OK, I am a Ruby noob, but I did get this fixed slightly differently than the answers here, so hopefully this helps someone else (tl;dr: I used RVM to switch the system Ruby version to the same one expected by rubygems).
First off, listing all Rubies as mentioned by Eimantas was a great starting point:
> which -a ruby
/opt/local/bin/ruby
/Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
/Users/Brian/.rvm/bin/ruby
/usr/bin/ruby
/opt/local/bin/ruby
The default Ruby instance in use by the system appeared to be 1.8.7:
> ruby -v
ruby 1.8.7 (2010-06-23 patchlevel 299) [i686-darwin10]
while the version in use by Rubygems was the 1.9.2 version managed by RVM:
> gem env | grep 'RUBY EXECUTABLE'
- RUBY EXECUTABLE: /Users/Brian/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
So that was definitely the issue. I don't actively use Ruby myself (this is simply a dependency of a build system script I'm trying to run) so I didn't care which version was active for other purposes. Since rubygems expected the 1.9.2 that was already managed by RVM, I simply used RVM to switch the system to use the 1.9.2 version as the default:
> rvm use 1.9.2
Using /Users/Brian/.rvm/gems/ruby-1.9.2-p290
> ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.3.0]
After doing that my "no such file" issue went away and my script started working.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
# plt.axis([x[0], x[-1], -1, 1]) # disable autoscaling
for point in x:
plt.plot(point, np.sin(2 * point), '.', color='b')
plt.draw()
plt.pause(0.01)
# plt.clf() # clear the current figure
if the amount of data is too much you can lower the update rate with a simple counter
cnt += 1
if (cnt == 10): # update plot each 10 points
plt.draw()
plt.pause(0.01)
cnt = 0
This was my actual problem that couldn't find satisfactory answer for, I wanted plotting that didn't close after the script was finished (like MATLAB),
If you think about it, after the script is finished, the program is terminated and there is no logical way to hold the plot this way, so there are two options
this wasn't satisfactory for me so I found another solution outside of the box
For this the saving and viewing should be both fast and the viewer shouldn't lock the file and should update the content automatically
vector based formats are both small and fast
For PDF there are several good options
On Windows I use SumatraPDF which is free, fast and light (only uses 1.8MB RAM for my case)
On Linux there are several options such as Evince (GNOME) and Ocular (KDE)
Sample code for outputing plot to a file
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(2 * x)
plt.plot(x, y)
plt.savefig("fig.pdf")
after first run, open the output file in one of the viewers mentioned above and enjoy.
Here is a screenshot of VSCode alongside SumatraPDF, also the process is fast enough to get semi-live update rate (I can get near 10Hz on my setup just use time.sleep()
between intervals)
I know this has been answered but none of these solutions worked for me. I needed to take a different approach. I am using PhoneGap and am compiling my code natively so I had to move the background to the body. I hope this helps someone else. Or if there a cleaner way to do this please feel free to comment...
$(document).on('shown.bs.modal', '.modal', function (e) {
$("#" + e.target.id).find(".modal-backdrop").css("z-index", $("#" + e.target.id).css("z-index")).insertBefore("#" + e.target.id);
});
That's no problem.
@Html.Partial("../Controller/View", model)
or
@Html.Partial("~/Views/Controller/View.cshtml", model)
Should do the trick.
If you want to pass through the (other) controller, you can use:
@Html.Action("action", "controller", parameters)
or any of the other overloads
if anyone else need the solution
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed(); return true;
}
return super.onOptionsItemSelected(item);
}
According to an article on Medium, this will work:
install --upgrade pandas==1.0.0rc0
It really depends on what is the binary itself going to do.
For example I want to create some listener.
The starting Daemon is simple task :
lis_deamon :
#!/bin/bash
# We will start the listener as Deamon process
#
LISTENER_BIN=/tmp/deamon_test/listener
test -x $LISTENER_BIN || exit 5
PIDFILE=/tmp/deamon_test/listener.pid
case "$1" in
start)
echo -n "Starting Listener Deamon .... "
startproc -f -p $PIDFILE $LISTENER_BIN
echo "running"
;;
*)
echo "Usage: $0 start"
exit 1
;;
esac
this is how we start the daemon (common way for all /etc/init.d/ staff)
now as for the listener it self, It must be some kind of loop/alert or else that will trigger the script to do what u want. For example if u want your script to sleep 10 min and wake up and ask you how you are doing u will do this with the
while true ; do sleep 600 ; echo "How are u ? " ; done
Here is the simple listener that u can do that will listen for your commands from remote machine and execute them on local :
listener :
#!/bin/bash
# Starting listener on some port
# we will run it as deamon and we will send commands to it.
#
IP=$(hostname --ip-address)
PORT=1024
FILE=/tmp/backpipe
count=0
while [ -a $FILE ] ; do #If file exis I assume that it used by other program
FILE=$FILE.$count
count=$(($count + 1))
done
# Now we know that such file do not exist,
# U can write down in deamon it self the remove for those files
# or in different part of program
mknod $FILE p
while true ; do
netcat -l -s $IP -p $PORT < $FILE |/bin/bash > $FILE
done
rm $FILE
So to start UP it : /tmp/deamon_test/listener start
and to send commands from shell (or wrap it to script) :
test_host#netcat 10.184.200.22 1024
uptime
20:01pm up 21 days 5:10, 44 users, load average: 0.62, 0.61, 0.60
date
Tue Jan 28 20:02:00 IST 2014
punt! (Cntrl+C)
Hope this will help.
Constraints for multiple views in playground.
swift 3+
var yellowView: UIView!
var redView: UIView!
override func loadView() {
// UI
let view = UIView()
view.backgroundColor = .white
yellowView = UIView()
yellowView.backgroundColor = .yellow
view.addSubview(yellowView)
redView = UIView()
redView.backgroundColor = .red
view.addSubview(redView)
// Layout
redView.translatesAutoresizingMaskIntoConstraints = false
yellowView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
yellowView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
yellowView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
yellowView.widthAnchor.constraint(equalToConstant: 80),
yellowView.heightAnchor.constraint(equalToConstant: 80),
redView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
redView.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -20),
redView.widthAnchor.constraint(equalToConstant: 80),
redView.heightAnchor.constraint(equalToConstant: 80)
])
self.view = view
}
In my opinion xcode playground is the best place for learning adding constraints programmatically.
Your condition says if X is greater than 57 AND smaller than 48
. X
cannot be both greater than 57 and smaller than 48 at the same time.
if(tmp[j] > 57 && tmp[j] < 48)
It should be if X is greater than 57 OR smaller than 48
:
if(tmp[j] > 57 || tmp[j] < 48)
Enable CORS on backend server or add chrome extensions https://chrome.google.com/webstore/search/CORS?utm_source=chrome-ntp-icon and make ON
try this out:
font-family: 'SF Pro Text',-apple-system,BlinkMacSystemFont,Roboto,'Segoe UI',Helvetica,Arial,sans-serif,'Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol';
It worked for me. ;) Do upvote if it works.
numpy has a sign function, and gives you a bonus of other functions as well. So:
import numpy as np
x = np.sign(y)
Just be careful that the result is a numpy.float64:
>>> type(np.sign(1.0))
<type 'numpy.float64'>
For things like json, this matters, as json does not know how to serialize numpy.float64 types. In that case, you could do:
float(np.sign(y))
to get a regular float.
Better and easy way.
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.cssSelector("a[href^='https://www.amazon.in/ap/signin']"))).contextClick().build().perform();
You can use any selector at the place of cssSelector
.
using System.IO;
using System.Text;
using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{
sw.WriteLine("my text...");
}
An alternate way of getting your encoding:
using System.IO;
using System.Text;
using (var sw = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
sw.WriteLine("my text...");
}
Check out the docs for the StreamWriter constructor.
I can provide two ways,
a.jsp,
<html>
<script language="javascript" type="text/javascript">
function call(){
var name = "xyz";
window.location.replace("a.jsp?name="+name);
}
</script>
<input type="button" value="Get" onclick='call()'>
<%
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}
%>
</html>
b.jsp,
<script>
var v="xyz";
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("value="+st);
%>
You maybe having this error on your java
files because there is one or more XML
file with error.
Go through all your XML
files and resolve errors, then clean
or rebuild
project from build menu
Start with your most recent edited XML
file
Here's a gist I put together. I was wondering the same and this helped improve my understanding. Open this up in an Xcode Playground to see what's going on.
protocol YelpRequestDelegate {
func getYelpData() -> AnyObject
func processYelpData(data: NSData) -> NSData
}
class YelpAPI {
var delegate: YelpRequestDelegate?
func getData() {
println("data being retrieved...")
let data: AnyObject? = delegate?.getYelpData()
}
func processYelpData(data: NSData) {
println("data being processed...")
let data = delegate?.processYelpData(data)
}
}
class Controller: YelpRequestDelegate {
init() {
var yelpAPI = YelpAPI()
yelpAPI.delegate = self
yelpAPI.getData()
}
func getYelpData() -> AnyObject {
println("getYelpData called")
return NSData()
}
func processYelpData(data: NSData) -> NSData {
println("processYelpData called")
return NSData()
}
}
var controller = Controller()
If this is an Observable being return in the HTML simply add the async pipe
observable | async
I use below sql to exclude the null string and empty string lines.
select * from table where length(nvl(column1,0))>0
Because, the length of empty string is 0.
select length('');
+-----------+--+
| length() |
+-----------+--+
| 0 |
+-----------+--+
/**
* Reverse LinkedList
* @author asharda
*
*/
class Node
{
int data;
Node next;
Node(int data)
{
this.data=data;
}
}
public class ReverseLinkedList {
static Node root;
Node temp=null;
public void insert(int data)
{
if(root==null)
{
root=new Node(data);
}
else
{
temp=root;
while(temp.next!=null)
{
temp=temp.next;
}
Node newNode=new Node(data);
temp.next=newNode;
}
}//end of insert
public void display(Node head)
{
while(head!=null)
{
System.out.println(head.data);
head=head.next;
}
}
public Node reverseLinkedList(Node head)
{
Node newNode;
Node tempr=null;
while(head!=null)
{
newNode=new Node(head.data);
newNode.next=tempr;
tempr=newNode;
head=head.next;
}
return tempr;
}
public static void main(String[] args) {
ReverseLinkedList r=new ReverseLinkedList();
r.insert(10);
r.insert(20);
r.insert(30);
r.display(root);
Node t=r.reverseLinkedList(root);
r.display(t);
}
}
Simply add method:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.destructive, title: "Delete") { (action, indexPath) in
self.arrayFruit.remove(at: indexPath.row)
self.tblList.reloadData()
}
let edit = UITableViewRowAction(style: UITableViewRowActionStyle.normal, title: "Edit") { (action, indexpath) in
let alert = UIAlertController(title: "FruitApp", message: "Enter Fuit Name", preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField(configurationHandler: { (textField) in
textField.placeholder = "Enter new fruit name"
})
alert.addAction(UIAlertAction(title: "Update", style: UIAlertActionStyle.default, handler: { [weak alert](_) in
let textField = alert?.textFields![0]
self.arrayFruit[indexPath.row] = (textField?.text!)!
self.tblList.reloadData()
}))
self.present(alert, animated: true, completion: nil)
}
edit.backgroundColor = UIColor.blue
return [delete,edit]
}
On Mac/Linux, you can easily convert a SVG file to a base64 encoded value for CSS background attribute with this simple bash command:
echo "background: transparent url('data:image/svg+xml;base64,"$(openssl base64 < path/to/file.svg)"') no-repeat center center;"
Tested on Mac OS X. This way you also avoid the URL escaping mess.
Remember that base64 encoding an SVG file increase its size, see css-tricks.com blog post.
You could use pandas.to_datetime()
as recommended in the documentation for pandas.read_csv()
:
If a column or index contains an unparseable date, the entire column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use
pd.to_datetime
afterpd.read_csv
.
Demo:
>>> D = {'date': '2013-6-4'}
>>> df = pd.DataFrame(D, index=[0])
>>> df
date
0 2013-6-4
>>> df.dtypes
date object
dtype: object
>>> df['date'] = pd.to_datetime(df.date, format='%Y-%m-%d')
>>> df
date
0 2013-06-04
>>> df.dtypes
date datetime64[ns]
dtype: object
I believe it would be like this
takedata.match(/(\[.+\])/g);
the g
at the end means global, so it doesn't stop at the first match.
I usually just specify this in an .htaccess
file or the vhost.conf
on the domain I'm working on. Add this to one of these files:
php_admin_value error_log "/var/www/vhosts/example.com/error_log"
Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img>
element placed under the canvas. To draw a background onto the canvas element you can do something like the following:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 903;
canvas.height = 657;
var background = new Image();
background.src = "http://www.samskirrow.com/background.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
// Draw whatever else over top of it on the canvas.
I've made an alternative to the other good answers on here that uses PowerShell, but mine also saves the list to a file. Will share it here in case anyone else needs wants something like that.
Warning: Code overwrites "longfilepath.txt" in the current working directory. I know it's unlikely you'd have one already, but just in case!
Purposely wanted it in a single line:
Out-File longfilepath.txt ; cmd /c "dir /b /s /a" | ForEach-Object { if ($_.length -gt 250) {$_ | Out-File -append longfilepath.txt}}
Detailed instructions:
cat longfilepath.txt | sort
Explanation:
Out-File longfilepath.txt ;
– Create (or overwrite) a blank file titled 'longfilepath.txt'. Semi-colon to separate commands.
cmd /c "dir /b /s /a" |
– Run dir command on PowerShell, /a
to show all files including hidden files. |
to pipe.
ForEach-Object { if ($_.length -gt 250) {$_ | Out-File -append longfilepath.txt}}
– For each line (denoted as $_), if the length is greater than 250, append that line to the file.
I think the classic answer is to create a more decoupled application, which has no knowledge of which implementation will be used during runtime.
For example, we're a central payment provider, working with many payment providers around the world. However, when a request is made, I have no idea which payment processor I'm going to call. I could program one class with a ton of switch cases, such as:
class PaymentProcessor{
private String type;
public PaymentProcessor(String type){
this.type = type;
}
public void authorize(){
if (type.equals(Consts.PAYPAL)){
// Do this;
}
else if(type.equals(Consts.OTHER_PROCESSOR)){
// Do that;
}
}
}
Now imagine that now you'll need to maintain all this code in a single class because it's not decoupled properly, you can imagine that for every new processor you'll support, you'll need to create a new if // switch case for every method, this only gets more complicated, however, by using Dependency Injection (or Inversion of Control - as it's sometimes called, meaning that whoever controls the running of the program is known only at runtime, and not complication), you could achieve something very neat and maintainable.
class PaypalProcessor implements PaymentProcessor{
public void authorize(){
// Do PayPal authorization
}
}
class OtherProcessor implements PaymentProcessor{
public void authorize(){
// Do other processor authorization
}
}
class PaymentFactory{
public static PaymentProcessor create(String type){
switch(type){
case Consts.PAYPAL;
return new PaypalProcessor();
case Consts.OTHER_PROCESSOR;
return new OtherProcessor();
}
}
}
interface PaymentProcessor{
void authorize();
}
** The code won't compile, I know :)
This is not exactly an answer, rather sharing my findings, and hopefully getting some critical argument for/against it, as specifically I am not aware how efficient it is.
I recently had a need to do this for my project. I did this using Object.assign
, more precisely it is done something like this:Object.assign(new Person(...), anObjectLikePerson)
.
Here is link to my JSFiddle, and also the main part of the code:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.getFullName = function() {
return this.lastName + ' ' + this.firstName;
}
}
var persons = [{
lastName: "Freeman",
firstName: "Gordon"
}, {
lastName: "Smith",
firstName: "John"
}];
var stronglyTypedPersons = [];
for (var i = 0; i < persons.length; i++) {
stronglyTypedPersons.push(Object.assign(new Person("", ""), persons[i]));
}
I also got the same issue with chrome, after adding DOCTYPE
it works as expected
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
Before
<?xml version="1.0" encoding="iso-8859-1"?>
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="792px" height="792px" viewBox="0 0 792 792" style="enable-background:new 0 0 792 792;" xml:space="preserve">
<g fill="none" stroke="black" stroke-width="15">
......
......
.......
</g>
</svg>
After
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="792px" height="792px" viewBox="0 0 792 792" style="enable-background:new 0 0 792 792;" xml:space="preserve">
<g fill="none" stroke="black" stroke-width="15">
......
......
.......
</g>
</svg>
You don't need to escape it inside. You can use the |
character to delimit searches.
"\"foo\"\'bar\'".replace(/("|')/g, "")
Try
//book[title/@lang = 'it']
This reads:
book
elements
title
lang
"it"
You may find this helpful — it's an article entitled "XPath in Five Paragraphs" by Ronald Bourret.
But in all honesty, //book[title[@lang='it']]
and the above should be equivalent, unless your XPath engine has "issues." So it could be something in the code or sample XML that you're not showing us -- for example, your sample is an XML fragment. Could it be that the root element has a namespace, and you aren't counting for that in your query? And you only told us that it didn't work, but you didn't tell us what results you did get.
While you are declaring onclick in XML then you must declair method and pass View v as parameter and make the method public...
Ex:
//in xml
android:onClick="onButtonClicked"
// in java file
public void onButtonClicked(View v)
{
//your code here
}
I want to add that if you are trying to do this for files/directories in a git repository to track if they have changed, then this is the best approach:
git log -1 --format=format:%H --full-diff <file_or_dir_name>
And if it's not a git-directory/repo, then answer by @ire_and_curses is probably the best bet:
tar c <dir_name> | md5sum
However, please note that tar
command will change the output hash if you run it in a different OS and stuff. If you want to be immune to that, this is the best approach, even though it doesn't look very elegant on first sight:
find <dir_name> -type f -print0 | sort -z | xargs -0 md5sum | md5sum | awk '{ print $1 }'
Here is how I solve this problem in a legacy application:
ng-options="kitType.name for kitType in vm.kitTypes track by kitType.id" ng-model="vm.itemTypeId"
vm.kitTypes = [
{"id": "1", "name": "Virtual"},
{"id": "2", "name": "Physical"},
{"id": "3", "name": "Hybrid"}
];
...
vm.itemTypeId = vm.kitTypes.filter(function(value, index, array){
return value.id === (vm.itemTypeId || 1);
})[0];
My HTML displays the option value properly.
The conflict message:
CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD
means that res/layout/dialog_item.xml
was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).
So you have to decide whether
git rm res/layout/dialog_item.xml
"or
git add res/layout/dialog_item.xml
"Then you finalize merge with "git commit
".
Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.
inplace=True
makes the function impure. It changes the original dataframe and returns None. In that case, You breaks the DSL chain.
Because most of dataframe functions return a new dataframe, you can use the DSL conveniently. Like
df.sort_values().rename().to_csv()
Function call with inplace=True
returns None and DSL chain is broken. For example
df.sort_values(inplace=True).rename().to_csv()
will throw NoneType object has no attribute 'rename'
Something similar with python’s build-in sort and sorted. lst.sort()
returns None
and sorted(lst)
returns a new list.
Generally, do not use inplace=True
unless you have specific reason of doing so. When you have to write reassignment code like df = df.sort_values()
, try attaching the function call in the DSL chain, e.g.
df = pd.read_csv().sort_values()...
There is a better answer to this problem, though I could just break this down step-by-step.
You will need to fetch and checkout the latest upstream changes like so, e.g.:
git fetch upstream
git checkout upstream/master -b revert/john/foo_and_bar
Taking a look at the commit log, you should find something similar to this:
commit b76a5f1f5d3b323679e466a1a1d5f93c8828b269 Merge: 9271e6e a507888 Author: Tim Tom <[email protected]> Date: Mon Apr 29 06:12:38 2013 -0700 Merge pull request #123 from john/foo_and_bar Add foo and bar commit a507888e9fcc9e08b658c0b25414d1aeb1eef45e Author: John Doe <[email protected]> Date: Mon Apr 29 12:13:29 2013 +0000 Add bar commit 470ee0f407198057d5cb1d6427bb8371eab6157e Author: John Doe <[email protected]> Date: Mon Apr 29 10:29:10 2013 +0000 Add foo
Now you want to revert the entire pull request with the ability to unrevert later. To do so, you will need to take the ID of the merge commit.
In the above example the merge commit is the top one where it says "Merged pull request #123...".
Do this to revert the both changes ("Add bar" and "Add foo") and you will end up with in one commit reverting the entire pull request which you can unrevert later on and keep the history of changes clean:
git revert -m 1 b76a5f1f5d3b323679e466a1a1d5f93c8828b269
I've created a bit of an adaptation of script @devnull69 submitted. I felt for my application it would be more useful as a function that returned the value that I could, then use as a variable.
HTML
<input type="text" id="time_field" />
<button>Submit</submit>
jQuery
$(document).ready(function() {
function convertTime(time) {
var hours = Number(time.match(/^(\d\d?)/)[1]);
var minutes = Number(time.match(/:(\d\d?)/)[1]);
var AMPM = time.match(/\s(AM|PM)$/i)[1];
if((AMPM == 'PM' || AMPM == 'pm') && hours < 12) {
hours = hours + 12;
}
else if((AMPM == 'AM' || AMPM == "am") && hours == 12) {
hours = hours - 12;
}
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours < 10) {
sHours = "0" + sHours;
}
else if(minutes < 10) {
sMinutes = "0" + sMinutes;
}
return sHours + ":" + sMinutes;
}
$('button').click(function() {
alert(convertTime($('#time_field').val()));
});
});
If you are using Visual Studio Community 2015 and trying to Install GLUT you should place the header file glut.h
in
C:\Program Files (x86)\Windows Kits\8.1\Include\um\gl
Given an instance of the struct, you set the values.
student thisStudent;
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
thisStudent.s_id = int.Parse(Console.ReadLine());
thisStudent.s_name = Console.ReadLine();
thisStudent.c_name = Console.ReadLine();
thisStudent.s_dob = Console.ReadLine();
Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.
Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.
I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.
Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.
In addition to @thoughtrepo's answer:
Until we do not have definitely typed events in React it might be useful to have a special target interface for input controls:
export interface FormControlEventTarget extends EventTarget{
value: string;
}
And then in your code cast to this type where is appropriate to have IntelliSense support:
import {FormControlEventTarget} from "your.helper.library"
(event.target as FormControlEventTarget).value;
If you have simple floats that you control the range of, you can also have an integer in the resources and divide by the number of decimal places you need straight in code.
So something like this
<integer name="strokeWidth">356</integer>
is used with 2 decimal places
this.strokeWidthFromResources = resources_.getInteger(R.integer.strokeWidth);
circleOptions.strokeWidth((float) strokeWidthFromResources/ 100);
and that makes it 3.56f
Not saying this is the most elegant solution but for simple projects, it's convenient.
Step 1 - Install package
# yum install MySQL-python
Loaded plugins: auto-update-debuginfo, langpacks, presto, refresh-packagekit
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package MySQL-python.i686 0:1.2.3-3.fc15 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
MySQL-python i686 1.2.3-3.fc15 fedora 78 k
Transaction Summary
================================================================================
Install 1 Package(s)
Total download size: 78 k
Installed size: 220 k
Is this ok [y/N]: y
Downloading Packages:
Setting up and reading Presto delta metadata
Processing delta metadata
Package(s) data still to download: 78 k
MySQL-python-1.2.3-3.fc15.i686.rpm | 78 kB 00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Installing : MySQL-python-1.2.3-3.fc15.i686 1/1
Installed:
MySQL-python.i686 0:1.2.3-3.fc15
Complete!
Step 2 - Test working
import MySQLdb
db = MySQLdb.connect("localhost","myusername","mypassword","mydb" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print "Database version : %s " % data
db.close()
Ouput:
Database version : 5.5.20
I know this question already have been answer but I have made some update to the GD function :
### COST FUNCTION
def cost(theta,X,y):
### Evaluate half MSE (Mean square error)
m = len(y)
error = np.dot(X,theta) - y
J = np.sum(error ** 2)/(2*m)
return J
cost(theta,X,y)
def GD(X,y,theta,alpha):
cost_histo = [0]
theta_histo = [0]
# an arbitrary gradient, to pass the initial while() check
delta = [np.repeat(1,len(X))]
# Initial theta
old_cost = cost(theta,X,y)
while (np.max(np.abs(delta)) > 1e-6):
error = np.dot(X,theta) - y
delta = np.dot(np.transpose(X),error)/len(y)
trial_theta = theta - alpha * delta
trial_cost = cost(trial_theta,X,y)
while (trial_cost >= old_cost):
trial_theta = (theta +trial_theta)/2
trial_cost = cost(trial_theta,X,y)
cost_histo = cost_histo + trial_cost
theta_histo = theta_histo + trial_theta
old_cost = trial_cost
theta = trial_theta
Intercept = theta[0]
Slope = theta[1]
return [Intercept,Slope]
res = GD(X,y,theta,alpha)
This function reduce the alpha over the iteration making the function too converge faster see Estimating linear regression with Gradient Descent (Steepest Descent) for an example in R. I apply the same logic but in Python.
Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:
In your BrowserWindow declaration, add the following webPreferences field:
i.e, instead of plain mainWindow = new BrowserWindow()
, write
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
What you need to do is this.
Your app's state will then be “Developer Removed From Sale”, and it will no longer be available on the App Store in any country.
I was thinking of a subclass of UserDict to automagically flat the keys.
class FlatDict(UserDict):
def __init__(self, *args, separator='.', **kwargs):
self.separator = separator
super().__init__(*args, **kwargs)
def __setitem__(self, key, value):
if isinstance(value, dict):
for k1, v1 in FlatDict(value, separator=self.separator).items():
super().__setitem__(f"{key}{self.separator}{k1}", v1)
else:
super().__setitem__(key, value)
? The advantages it that keys can be added on the fly, or using standard dict instanciation, without surprise:
?
>>> fd = FlatDict(
... {
... 'person': {
... 'sexe': 'male',
... 'name': {
... 'first': 'jacques',
... 'last': 'dupond'
... }
... }
... }
... )
>>> fd
{'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond'}
>>> fd['person'] = {'name': {'nickname': 'Bob'}}
>>> fd
{'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond', 'person.name.nickname': 'Bob'}
>>> fd['person.name'] = {'civility': 'Dr'}
>>> fd
{'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond', 'person.name.nickname': 'Bob', 'person.name.civility': 'Dr'}
This example might help you. by using simple casting you can get code behind urdu character.
string str = "?????";
char ch = ' ';
int number = 0;
for (int i = 0; i < str.Length; i++)
{
ch = str[i];
number = (int)ch;
Console.WriteLine(number);
}
OK, got it working. Turns out that an NTFS volume where the DB files were located got heavily fragmented. Stopped SQL Server, defragmented the whole thing and all it was fine ever since.
I have found this to be a useful pattern to follow:
@RunWith(SpringRunner)
@SpringBootTest(classes = [ TestConfiguration, MyApplication ],
properties = [
"spring.config.name=application-MyTest_LowerImportance,application-MyTest_MostImportant"
,"debug=true", "trace=true"
]
)
Here we override the use of "application.yml" to use "application-MyTest_LowerImportance.yml" and also "application-MyTest_MostImportant.yml"
(Spring will also look for .properties files)
Also included as an extra bonus are the debug and trace settings, on a separate line so you can comment them out if required ;]
The debug/trace are incredibly useful as Spring will dump the names of all the files it loads and those it tries to load.
You will see lines like this in the console at runtime:
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant.properties' (file:./config/application-MyTest_MostImportant.properties) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant.xml' (file:./config/application-MyTest_MostImportant.xml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant.yml' (file:./config/application-MyTest_MostImportant.yml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant.yaml' (file:./config/application-MyTest_MostImportant.yaml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_LowerImportance.properties' (file:./config/application-MyTest_LowerImportance.properties) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_LowerImportance.xml' (file:./config/application-MyTest_LowerImportance.xml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_LowerImportance.yml' (file:./config/application-MyTest_LowerImportance.yml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_LowerImportance.yaml' (file:./config/application-MyTest_LowerImportance.yaml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_MostImportant.properties' (file:./application-MyTest_MostImportant.properties) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_MostImportant.xml' (file:./application-MyTest_MostImportant.xml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_MostImportant.yml' (file:./application-MyTest_MostImportant.yml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_MostImportant.yaml' (file:./application-MyTest_MostImportant.yaml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_LowerImportance.properties' (file:./application-MyTest_LowerImportance.properties) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_LowerImportance.xml' (file:./application-MyTest_LowerImportance.xml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_LowerImportance.yml' (file:./application-MyTest_LowerImportance.yml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_LowerImportance.yaml' (file:./application-MyTest_LowerImportance.yaml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_MostImportant.properties' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_MostImportant.xml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_MostImportant.yml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_MostImportant.yaml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.properties' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.xml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.yml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.yaml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_MostImportant.properties' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_MostImportant.xml' resource not found
DEBUG 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Loaded config file 'file:/Users/xxx/dev/myproject/target/test-classes/application-MyTest_MostImportant.yml' (classpath:/application-MyTest_MostImportant.yml)
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_MostImportant.yaml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_LowerImportance.properties' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_LowerImportance.xml' resource not found
DEBUG 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Loaded config file 'file:/Users/xxx/dev/myproject/target/test-classes/application-MyTest_LowerImportance.yml' (classpath:/application-MyTest_LowerImportance.yml)
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_LowerImportance.yaml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant-test.properties' (file:./config/application-MyTest_MostImportant-test.properties) resource not found
I know this is pretty old but in java 8:
LocalTime.MIN.plusSeconds(120).format(DateTimeFormatter.ISO_LOCAL_TIME)
How big is your sample? Here is another option to test your data against any distribution using OpenTURNS library. In the example below, I generate a sample x of 1.000.000 numbers from a Uniform distribution and test it against a Normal distribution.
You can replace x by your data if you reshape it as x= [[x1], [x2], .., [xn]]
import openturns as ot
x = ot.Uniform().getSample(1000000)
g = ot.VisualTest.DrawQQplot(x, ot.Normal())
g
In my Jupyter Notebook, I see:
If you are writing a script, you can do it more properly
from openturns.viewer import View`
import matplotlib.pyplot as plt
View(g)
plt.show()
You can also use the subset function:
data <- subset(data, select=c(3,2,1))
You should better use the [] operator as in the other answers, but it may be useful to know that you can do a subset and a column reorder operation in a single command.
Update:
You can also use the select function from the dplyr package:
data = data %>% select(Time, out, In, Files)
I am not sure about the efficiency, but thanks to dplyr's syntax this solution should be more flexible, specially if you have a lot of columns. For example, the following will reorder the columns of the mtcars dataset in the opposite order:
mtcars %>% select(carb:mpg)
And the following will reorder only some columns, and discard others:
mtcars %>% select(mpg:disp, hp, wt, gear:qsec, starts_with('carb'))
Read more about dplyr's select syntax.
mydict = {
'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
'Grapes':{'Arabian':'25','Indian':'20'} }
for n in mydict:
print(mydict[n])
The OP asked, is it possible to reference a table, not how to add a table. So the working equivalent of
Sheets("Sheet1").Table("A_Table").Select
would be this statement:
Sheets("Sheet1").ListObjects("A_Table").Range.Select
or to select parts (like only the data in the table):
Dim LO As ListObject
Set LO = Sheets("Sheet1").ListObjects("A_Table")
LO.HeaderRowRange.Select ' Select just header row
LO.DataBodyRange.Select ' Select just data cells
LO.TotalsRowRange.Select ' Select just totals row
For the parts, you may want to test for the existence of the header and totals rows before selecting them.
And seriously, this is the only question on referencing tables in VBA in SO? Tables in Excel make so much sense, but they're so hard to work with in VBA!
Late answer, but hopefully worthwhile: The Poor Man's T-SQL Formatter is an open-source (free) T-SQL formatter with complete T-SQL batch/script support (any DDL, any DML), SSMS Plugin, command-line bulk formatter, and other options.
It's available for immediate/online use at http://poorsql.com, and just today graduated to "version 1.0" (it was in beta version for a few months), having just acquired support for MERGE
statements, OUTPUT
clauses, and other finicky stuff.
The SSMS Add-in allows you to set your own hotkey (default is Ctrl-K, Ctrl-F, to match Visual Studio), and formats the entire script or just the code you have selected/highlighted, if any. Output formatting is customizable.
In SSMS 2008 it combines nicely with the built-in intelli-sense, effectively providing more-or-less the same base functionality as Red Gate's SQL Prompt (SQL Prompt does, of course, have extra stuff, like snippets, quick object scripting, etc).
Feedback/feature requests are more than welcome, please give it a whirl if you get the chance!
Disclosure: This is probably obvious already but I wrote this library/tool/site, so this answer is also shameless self-promotion :)
This error happened to me, generally it'll be a problem due to not including the mysql-connector.jar in your eclipse project (or your IDE).
In my case, it was because of a problem on the OS.
I was editing a table in phpmyadmin, and mysql hung, I restarted Ubuntu. I cleaned the project without being successful. This morning, when I've tried the web server, it work perfectly the first time.
At the first reboot, the OS recognized that there was a problem, and after the second one, it was fixed. I hope this will save some time to somebody that "could" have this problem!
One of most upleasing functional forEach
's limitations is lack of checked exceptions support.
One possible workaround is to replace terminal forEach
with plain old foreach loop:
Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
Iterable<String> iterable = stream::iterator;
for (String s : iterable) {
fileWriter.append(s);
}
Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:
Java 8 Lambda function that throws exception?
Java 8: Lambda-Streams, Filter by Method with Exception
How can I throw CHECKED exceptions from inside Java 8 streams?
Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?
Noticed this is a 2-years old question, but still want to share my workaround for this particular question:
Firstly, run docker container ls -a
to list all the containers you have and pinpoint the want you want to delete.
Secondly, delete the one with command docker container rm <CONTAINER ID>
(If the container is currently running, you should stop it first, run docker container stop <CONTAINER ID>
to gracefully stop the specified container, if it does not stop it for whatever the reason is, alternatively you can run docker container kill <CONTAINER ID> to force shutdown of the specified container
).
Thirdly, remove the container by running docker container rm <CONTAINER ID>
.
Lastly you can run docker image ls -a
to view all the images and delete the one you want to by running docker image rm <hash>
.
I come across a situation where i need to insert the data in the database & simultaneously require the primary id using entity framework. Solution :
long id;
IGenericQueryRepository<myentityclass, Entityname> InfoBase = null;
try
{
InfoBase = new GenericQueryRepository<myentityclass, Entityname>();
InfoBase.Add(generalinfo);
InfoBase.Context.SaveChanges();
id = entityclassobj.ID;
return id;
}
You could also use
print(tbl_df(df), n=40)
or with the help of the pipe operator
df %>% tbl_df %>% print(n=40)
To print all rows specify tbl_df %>% print(n = Inf)
Simply just enter any of below in the command line,
ng --version
ORng v
ORng -v
The Output would be like,
Not only the Angular version but also the Node version is also mentioned there. I use Angular 6.
git rebase -i YOUR_FIRTS_COMMIT_SHA^
while true; do git commit --amend --author="Name Surname <[email protected]>" --no-edit && git rebase --continue; done
Press ^C # after the rebase is done (the loop will keep updating last commit)
I have the same error the result of command :
file hadoop-2.7.2.tar.gz
is hadoop-2.7.2.tar.gz: HTML document, ASCII text
the reason that the file is not gzip format due to problem in download or other.
The post Reset Demystified in the blog Pro Git gives a very no-brainer explanation on git reset
and git checkout
.
After all the helpful discussion at the top of that post, the author reduces the rules to the following simple three steps:
That is basically it. The
reset
command overwrites these three trees in a specific order, stopping when you tell it to.
- Move whatever branch HEAD points to (stop if
--soft
)- THEN, make the Index look like that (stop here unless
--hard
)- THEN, make the Working Directory look like that
There are also
--merge
and--keep
options, but I would rather keep things simpler for now - that will be for another article.
Use the following code for getting lat and long using php. Here are two methods:
<?php
// Get lat and long by address
$address = $dlocation; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
?>
edit - Google Maps requests must be over https
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(50.804400, -1.147250);
var mapOptions = {
zoom: 6,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
}
function codeAddress(address,tutorname,url,distance,prise,postcode) {
var address = address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
});
infowindow.open(map,marker);
} /*else {
alert('Geocode was not successful for the following reason: ' + status);
}*/
});
}
google.maps.event.addDomListener(window, 'load', initialize);
window.onload = function(){
initialize();
// your code here
<?php foreach($addr as $add) {
?>
codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
<?php } ?>
};
</script>
<div id="map-canvas12"></div>
Doesn't answer the question directly, but I found this question when searching for a way to, basically, not re-enter the password every single time I pull on a remote server.
Well, git
allows you to cache your credentials for a finite amount of time. It's customizable in git config
and this page explains it very well:
https://help.github.com/articles/caching-your-github-password-in-git/#platform-linux
In a terminal, run:
$ git config --global credential.helper cache
# Set git to use the credential memory cache
To customize the cache timeout, you can do:
$ git config --global credential.helper 'cache --timeout=3600'
# Set the cache to timeout after 1 hour (setting is in seconds)
Your credentials will then be stored in-memory for the requested amount of time.
An elegant option is writing an extension method (see below) for the DataTable class of .net framework.
This extention method can be called as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data;
using System.Data.OleDb;
DataTable dt;
// fill table data in dt here
...
// export DataTable to excel
// save excel file without ever making it visible if filepath is given
// don't save excel file, just make it visible if no filepath is given
dt.ExportToExcel(ExcelFilePath);
Extension method for DataTable class:
public static class My_DataTable_Extensions
{
// Export DataTable into an excel file with field names in the header line
// - Save excel file without ever making it visible if filepath is given
// - Don't save excel file, just make it visible if no filepath is given
public static void ExportToExcel(this DataTable tbl, string excelFilePath = null) {
try {
if (tbl == null || tbl.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
var excelApp = new Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Excel._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (var i = 0; i < tbl.Columns.Count; i++) {
workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
}
// rows
for (var i = 0; i < tbl.Rows.Count; i++) {
// to do: format datetime values before printing
for (var j = 0; j < tbl.Columns.Count; j++) {
workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
}
}
// check file path
if (!string.IsNullOrEmpty(excelFilePath)) {
try {
workSheet.SaveAs(excelFilePath);
excelApp.Quit();
MessageBox.Show("Excel file saved!");
}
catch (Exception ex) {
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
} else { // no file path is given
excelApp.Visible = true;
}
}
catch (Exception ex) {
throw new Exception("ExportToExcel: \n" + ex.Message);
}
}
}
If you can't or don't want to use any AJAX stuff, use an iframe or ten! ;) You can have processes running in iframes in parallel with the master page without worrying about cross browser comparable issues or syntax issues with dot net AJAX etc, and you can call the master page's JavaScript (including the JavaScript that it has imported) from an iframe.
E.g, in a parent iframe, to call egFunction()
in the parent document once the iframe content has loaded (that's the asynchronous part)
parent.egFunction();
Dynamically generate the iframes too so the main html code is free from them if you want.
There is 'ncftp' which is available for installation in linux. This works on the FTP protocol and can be used to download files and folders recursively. works on linux. Has been used and is working fine for recursive folder/file transfer.
Check this link... http://www.ncftp.com/
You can apply only to certain attribute by doing:
input[type="checkbox"] {...}
It explains it here.
get_user_name works the same way as getenv('USERNAME');
I had encoding(with cyrillic) problems using getenv('USERNAME')
The easiest and the most correct (and legal) way is to use graph api.
Just perform the request: http://graph.facebook.com/4
which returns
{
"id": "4",
"name": "Mark Zuckerberg",
"first_name": "Mark",
"last_name": "Zuckerberg",
"link": "http://www.facebook.com/zuck",
"username": "zuck",
"gender": "male",
"locale": "en_US"
}
and take the link
key.
You can also reduce the traffic by using fields
parameter: http://graph.facebook.com/4?fields=link to get only what you need:
{
"link": "http://www.facebook.com/zuck",
"id": "4"
}
It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.
For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.
Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command
You can use this
<a onClick={() => {window.location.href="/something"}}>Something</a>
If you use Google Guava (and if you don't, you should), you can call: ByteStreams.toByteArray(InputStream)
or Files.toByteArray(File)
On Excel 2010 try this: