Depending on your needs, you want to use their section feeds, their search feeds
http://news.google.com/news?q=apple&output=rss
or Bing News Search.
Some facts:
Google offers a public search webservice API which returns JSON: http://ajax.googleapis.com/ajax/services/search/web. Documentation here
Java offers java.net.URL
and java.net.URLConnection
to fire and handle HTTP requests.
JSON can in Java be converted to a fullworthy Javabean object using an arbitrary Java JSON API. One of the best is Google Gson.
Now do the math:
public static void main(String[] args) throws Exception {
String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String search = "stackoverflow";
String charset = "UTF-8";
URL url = new URL(google + URLEncoder.encode(search, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
// Show title and URL of 1st result.
System.out.println(results.getResponseData().getResults().get(0).getTitle());
System.out.println(results.getResponseData().getResults().get(0).getUrl());
}
With this Javabean class representing the most important JSON data as returned by Google (it actually returns more data, but it's left up to you as an exercise to expand this Javabean code accordingly):
public class GoogleResults {
private ResponseData responseData;
public ResponseData getResponseData() { return responseData; }
public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
public String toString() { return "ResponseData[" + responseData + "]"; }
static class ResponseData {
private List<Result> results;
public List<Result> getResults() { return results; }
public void setResults(List<Result> results) { this.results = results; }
public String toString() { return "Results[" + results + "]"; }
}
static class Result {
private String url;
private String title;
public String getUrl() { return url; }
public String getTitle() { return title; }
public void setUrl(String url) { this.url = url; }
public void setTitle(String title) { this.title = title; }
public String toString() { return "Result[url:" + url +",title:" + title + "]"; }
}
}
###See also:
Update since November 2010 (2 months after the above answer), the public search webservice has become deprecated (and the last day on which the service was offered was September 29, 2014). Your best bet is now querying http://www.google.com/search directly along with a honest user agent and then parse the result using a HTML parser. If you omit the user agent, then you get a 403 back. If you're lying in the user agent and simulate a web browser (e.g. Chrome or Firefox), then you get a way much larger HTML response back which is a waste of bandwidth and performance.
Here's a kickoff example using Jsoup as HTML parser:
String google = "http://www.google.com/search?q=";
String search = "stackoverflow";
String charset = "UTF-8";
String userAgent = "ExampleBot 1.0 (+http://example.com/bot)"; // Change this to your company's name and bot homepage!
Elements links = Jsoup.connect(google + URLEncoder.encode(search, charset)).userAgent(userAgent).get().select(".g>.r>a");
for (Element link : links) {
String title = link.text();
String url = link.absUrl("href"); // Google returns URLs in format "http://www.google.com/url?q=<url>&sa=U&ei=<someKey>".
url = URLDecoder.decode(url.substring(url.indexOf('=') + 1, url.indexOf('&')), "UTF-8");
if (!url.startsWith("http")) {
continue; // Ads/news/etc.
}
System.out.println("Title: " + title);
System.out.println("URL: " + url);
}
If you have OS(64bit) and SSMS(64bit) and already install the AccessDatabaseEngine(64bit) and you still received an error, try this following solutions:
1: direct opening the sql server import and export wizard.
if you able to connect using direct sql server import and export wizard, then importing from SSMS is the issue, it's like activating 32bit if you import data from SSMS.
Instead of installing AccessDatabaseEngine(64bit) , try to use the AccessDatabaseEngine(32bit) , upon installation, windows will stop you for continuing the installation if you already have another app installed , if so , then use the following steps. This is from the MICROSOFT. The Quiet Installation.
If Office 365 is already installed, side by side detection will prevent the installation from proceeding. Instead perform a /quiet install of these components from command line. To do so, download the desired AccessDatabaseEngine.exe or AccessDatabaeEngine_x64.exe to your PC, open an administrative command prompt, and provide the installation path and switch Ex: C:\Files\AccessDatabaseEngine.exe /quiet
or check in the Addition Information content from the link below,
https://www.microsoft.com/en-us/download/details.aspx?id=54920
You can animate the scrolltop of the page with jQuery.
$('html, body').animate({
scrollTop: $(".middle").offset().top
}, 2000);
See this site: http://papermashup.com/jquery-page-scrolling/
I found for my particular setup the following commands worked
brew doctor
And then that showed me where my errors were, and then this slightly different command from the comment above.
sudo chown -R $(whoami) /usr/local/opt
ALL YOU HAVE TO DO:
HTML:
<table id="my-table"><tr>
<td> CELL 1 With a lot of text in it</td>
<td> CELL 2 </td>
<td> CELL 3 </td>
<td> CELL 4 With a lot of text in it </td>
<td> CELL 5 </td>
</tr></table>
CSS:
#my-table{width:100%;} /*or whatever width you want*/
#my-table td{width:2000px;} /*something big*/
if you have th
you need to set it too like this:
#my-table th{width:2000px;}
In my case adding sudo before npm install solved gulp command not found problem
sudo npm install
When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe
I had to choose the following options to get the management Tools:
When I was done I had an option "SQL Server Management Studio" within my Start Menu.
Searching for "Management" pulled it up faster within the Start Menu.
You can try this
select count( distinct pos) from
(select instr('123-456-789', '-', level) as pos from dual
connect by level <=length('123-456-789'))
where nvl(pos, 0) !=0
it counts "properly" olso for how many 'aa' in 'bbaaaacc'
select count( distinct pos) from
(select instr('bbaaaacc', 'aa', level) as pos from dual
connect by level <=length('bbaaaacc'))
where nvl(pos, 0) !=0
The below function would return '0' if there is no match and a 'positive integer' in case of matching:
Function IsInArray(stringToBeFound As String, arr As Variant) As Integer
IsInArray = InStr(Join(arr, ""), stringToBeFound)
End Function
______________________________________________________________________________
Note: the function first concatenates the entire array content to a string using 'Join' (not sure if the join method uses looping internally or not) and then checks for a macth within this string using InStr.
Is there such a thing as destructors for ECMAScript 6?
No. EcmaScript 6 does not specify any garbage collection semantics at all[1], so there is nothing like a "destruction" either.
If I register some of my object's methods as event listeners in the constructor, I want to remove them when my object is deleted
A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered.
What you are actually looking for is a method of registering listeners without marking them as live root objects. (Ask your local eventsource manufacturer for such a feature).
1): Well, there is a beginning with the specification of WeakMap
and WeakSet
objects. However, true weak references are still in the pipeline [1][2].
Open the AVD Manager.
Click Edit Icon to edit the AVD.
Click Show Advanced settings.
Change the Internal Storage, Ram, SD Card size as necessary. Click Finish.
Confirm the popup by clicking yes.
Wipe Data on the AVD and confirm the popup by clicking yes.
Important: After increasing the size, if it doesn't automatically ask you to wipe data, you have to do it manually by opening the AVD's pull-down menu and choosing Wipe Data.
Now start and use your Emulator with increased storage.
func readToDisplayUsingFile1(f *os.File){
defer f.Close()
reader := bufio.NewReader(f)
contents, _ := ioutil.ReadAll(reader)
lines := strings.Split(string(contents), '\n')
}
or
func readToDisplayUsingFile1(f *os.File){
defer f.Close()
slice := make([]string,0)
reader := bufio.NewReader(f)
for{
str, err := reader.ReadString('\n')
if err == io.EOF{
break
}
slice = append(slice, str)
}
Ok, you are trying to access the GUI via another thread. This, in the main, is not good practice.
The AsyncTask executes everything in doInBackground()
inside of another thread, which does not have access to the GUI where your views are.
preExecute()
and postExecute()
offer you access to the GUI before and after the heavy lifting occurs in this new thread, and you can even pass the result of the long operation to postExecute()
to then show any results of processing.
See these lines where you are later updating your TextView:
TextView txt = findViewById(R.id.output);
txt.setText("Executed");
Put them in onPostExecute()
.
You will then see your TextView text updated after the doInBackground
completes.
I noticed that your onClick listener does not check to see which View has been selected. I find the easiest way to do this is via switch statements. I have a complete class edited below with all suggestions to save confusion.
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class AsyncTaskActivity extends Activity implements OnClickListener {
Button btn;
AsyncTask<?, ?, ?> runningTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = findViewById(R.id.button1);
// Because we implement OnClickListener, we only
// have to pass "this" (much easier)
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// Detect the view that was "clicked"
switch (view.getId()) {
case R.id.button1:
if (runningTask != null)
runningTask.cancel(true);
runningTask = new LongOperation();
runningTask.execute();
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Cancel running task(s) to avoid memory leaks
if (runningTask != null)
runningTask.cancel(true);
}
private final class LongOperation extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// We were cancelled; stop sleeping!
}
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed"); // txt.setText(result);
// You might want to change "executed" for the returned string
// passed into onPostExecute(), but that is up to you
}
}
}
There are two different ways to use delay in selenium one which is most commonly in use. Please try this:
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
second one which you can use that is simply try catch method by using that method you can get your desire result.if you want example code feel free to contact me defiantly I will provide related code
If you have wamp installed then go to command prompt , go to the path where mysql.exe exists , like for me it was : C:\wamp\bin\mysql\mysql5.0.51b\bin , then paste the sql file in the same location and then run this command in cmd :
C:\wamp\bin\mysql\mysql5.0.51b\bin>mysql -u root -p YourDatabaseName < YourFileName.sql
By reading your exception , It's sure that you forgot to autowire customerService
You should autowire your customerservice .
make following changes in your controller class
@Controller
public class CustomerController{
@Autowired
private Customerservice customerservice;
......other code......
}
Again your service implementation class
write
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerDAO customerDAO;
......other code......
.....add transactional methods
}
If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).
you should autowire sessionFactory set method in your DAO mplementation
please find samle application context :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.sparkle" />
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" /> -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
</beans>
note that i am using jdbc.properties file for jdbc url and driver specification
I can replace all query parameters with this single line: $location.search({});
Easy to understand and easy way to clear them out.
Store the previous scroll location, then see if the new one is greater than or less than that.
Here's a way to avoid any global variables (fiddle available here):
(function () {
var previousScroll = 0;
$(window).scroll(function(){
var currentScroll = $(this).scrollTop();
if (currentScroll > previousScroll){
alert('down');
} else {
alert('up');
}
previousScroll = currentScroll;
});
}()); //run this anonymous function immediately
Try details: use any option..
MessageBox.Show("your message",
"window title",
MessageBoxButtons.OK,
MessageBoxIcon.Warning // for Warning
//MessageBoxIcon.Error // for Error
//MessageBoxIcon.Information // for Information
//MessageBoxIcon.Question // for Question
);
Yet another solution:
I was stumped because I was including boost_regex-vc120-mt-gd-1_58.lib in my Link->Additional Dependencies property, but the link kept telling me it couldn't open libboost_regex-vc120-mt-gd-1_58.lib (note the lib prefix). I didn't specify libboost_regex-vc120-mt-gd-1_58.lib.
I was trying to use (and had built) the boost dynamic libraries (.dlls) but did not have the BOOST_ALL_DYN_LINK macro defined. Apparently there are hints in the compile to include a library, and without BOOST_ALL_DYN_LINK it looks for the static library (with the lib prefix), not the dynamic library (without a lib prefix).
To do with javascript you could do something like this:
<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>
Then you can use whatever you want in your javascript to put the text var into the textbox.
If you aren't dynamically loading scripts or marking them as defer
or async
, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.
Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.
There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.
When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.
A script tag with async
may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async
is that it can run anytime and that time is not predictable.
A script tag with defer
waits until the entire parser is done and then runs all scripts marked with defer
in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer
. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer
like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer
or async
.
Here's a quote from that article:
script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.
The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.
A quote from the HTML5 spec:
Then, the first of the following options that describes the situation must be followed:
If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.
The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)
The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)
Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.
The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:
If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.
Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.
Remove the first element from this list of scripts that will execute in order as soon as possible.
If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.
If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.
The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.
Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.
What about Javascript module scripts, type="module"
?
Javascript now has support for module loading with syntax like this:
<script type="module">
import {addTextToBody} from './utils.mjs';
addTextToBody('Modules are pretty cool.');
</script>
Or, with src
attribute:
<script type="module" src="http://somedomain.com/somescript.mjs">
</script>
All scripts with type="module"
are automatically given the defer
attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.
Module scripts can also be given the async
attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async
script in any particular order relative to other scripts.
There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.
I had the same issue and atom-goto-definition (package name goto-definition) worked like charm for me. Please try once. You can download directly from Atom.
This package is DEPRECATED. Please check it in Github.
The problem is you either haven't closed your if
or you need an elseif
:
create procedure checando(
in nombrecillo varchar(30),
in contrilla varchar(30),
out resultado int)
begin
if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
set resultado = 0;
elseif exists (select * from compas where nombre = nombrecillo) then
set resultado = -1;
else
set resultado = -2;
end if;
end;
@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000
If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:
...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'
or
...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06'
AND usagetime < '2012-09-03 08:03:07'
You can get all the required file properties by using the code below:
FOR %%? IN (file_to_be_queried) DO (
ECHO File Name Only : %%~n?
ECHO File Extension : %%~x?
ECHO Name in 8.3 notation : %%~sn?
ECHO File Attributes : %%~a?
ECHO Located on Drive : %%~d?
ECHO File Size : %%~z?
ECHO Last-Modified Date : %%~t?
ECHO Parent Folder : %%~dp?
ECHO Fully Qualified Path : %%~f?
ECHO FQP in 8.3 notation : %%~sf?
ECHO Location in the PATH : %%~dp$PATH:?
)
$('.tabDisable').on('keydown', function(e)
{
if (e.keyCode == 9)
{
e.preventDefault();
}
});
Put .tabDisable to all tab disable DIVs Like
<div class='tabDisable'>First Div</div> <!-- Tab Disable Div -->
<div >Second Div</div> <!-- No Tab Disable Div -->
<div class='tabDisable'>Third Div</div> <!-- Tab Disable Div -->
You can use the folowing code:
def float_range(initVal, itemCount, step):
for x in xrange(itemCount):
yield initVal
initVal += step
[x for x in float_range(1, 3, 0.1)]
int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];
This is one of many ways.
I don't know if this is the correct way however I did this:
<div class="control-group">
<label class="control-label" for="id1">Label:</label>
<div class="controls">
<textarea id="id1" class="textareawidth" rows="10" name="anyname">value</textarea>
</div>
</div>
and put this in my bootstrapcustom.css file:
@media (min-width: 768px) {
.textareawidth {
width:500px;
}
}
@media (max-width: 767px) {
.textareawidth {
}
}
This way it resizes based on the viewport. Seems to line everything up nicely on a big browser and on a small mobile device.
NPM
- Manages packages but doesn't make life easy executing any.NPX
- A tool for executing Node packages.
NPX
comes bundled withNPM
version5.2+
NPM
by itself does not simply run any package. it doesn't run any package in a matter of fact. If you want to run a package using NPM, you must specify that package in your package.json
file.
When executables are installed via NPM packages, NPM links to them:
./node_modules/.bin/
directory.bin/
directory (e.g. /usr/local/bin
) on Linux or at %AppData%/npm
on Windows.One might install a package locally on a certain project:
npm install some-package
Now let's say you want NodeJS to execute that package from the command line:
$ some-package
The above will fail. Only globally installed packages can be executed by typing their name only.
To fix this, and have it run, you must type the local path:
$ ./node_modules/.bin/some-package
You can technically run a locally installed package by editing your packages.json
file and adding that package in the scripts
section:
{
"name": "whatever",
"version": "1.0.0",
"scripts": {
"some-package": "some-package"
}
}
Then run the script using npm run-script
(or npm run
):
npm run some-package
npx
will check whether <command>
exists in $PATH
, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package some-package
all you need to do is type:
npx some-package
Another major advantage of npx
is the ability to execute a package which wasn't previously installed:
$ npx create-react-app my-app
The above example will generate a react
app boilerplate within the path the command had run in, and ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.
npx
command may be helpful in the script
section of a package.json
file,
when it is unwanted to define a dependency which might not be commonly used or any other reason:
"scripts": {
"start": "npx [email protected]",
"serve": "npx http-server"
}
Call with: npm run serve
I was able to piece together information from everyone here and further Googling, and I came up with the following which works in Chrome and Firefox: http://jsfiddle.net/xtbmpcsu/. I'm still working on making this work for IE and Opera.
The key is putting the content inside of the div to which the filter is applied:
<div id="mask">
<p>Lorem ipsum ...</p>
<img src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
</div>
And then the CSS:
body {
background: #300000;
background: linear-gradient(45deg, #300000, #000000, #300000, #000000);
color: white;
}
#mask {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: black;
opacity: 0.5;
}
img {
filter: blur(10px);
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
position: absolute;
left: 100px;
top: 100px;
height: 300px;
width: auto;
}
So mask has the filters applied. Also, note the use of url() for a filter with an <svg>
tag for the value -- that idea came from http://codepen.io/AmeliaBR/pen/xGuBr. If you happen to minify your CSS, you might need to replace any spaces in the SVG filter markup with "%20".
So now, everything inside the mask div is blurred.
The in
operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.each
. In this specific case, you have to parse the JSON:
$.each(JSON.parse(myData), ...);
yesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
eiteText=(EditText)findViewById(R.id.nameET);
String result=eiteText.getText().toString();
Log.d("TAG",result);
}
});
Run the following commands in guest machine/VM:
wget https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub -O ~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chown -R vagrant:vagrant ~/.ssh
Then do vagrant halt. This will remove and regenerate your private keys.
(These steps assume you have already created or already have the ~/.ssh/ and ~/.ssh/authorized_keys directories under your home folder.)
Use Google Search Operators to find it for you
search google with the below code..
inurl:domain.com filetype:xml click on this to view sitemap search example
change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)
I've encountered this problem when the build is abruptly closed before it is loaded. No process would show up in the Task Manager, but if you navigate to the executable generated in the project folder and try to delete it, Windows claims that the application is in use. (If not, just delete the file and rebuild, which generates a new executable) In Windows(Visual Studio 2019), the file is located in this directory by default:
%USERPROFILE%\source\repos\ProjectFolderName\Debug
To end the allegedly running process, open the command prompt and type in the following command:
taskkill /F /IM ApplicationName.exe
This forces any running instance to be terminated. Rebuild and execute!
Those are users. Check your /etc/passwd
.
cd ~username
takes you to that user's home directory.
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
128 characters. This is the max length of the sysname
datatype (nvarchar(128)
).
Pull and push again:
git pull; git push
Push into different branch:
git push origin master:foo
and merge it on remote (either by git
or pull-request)
git merge foo
Force it (not recommended unless you deliberately changed commits via rebase
):
git push origin master -f
If still refused, disable denyCurrentBranch
on remote repository:
git config receive.denyCurrentBranch ignore
I was passing the values without the quotes. Once I passed the conditions inside the single quotes worked like a charm.
Select * from emp_table where emp_id=123;
instead of the above use this:
Select * from emp_table where emp_id='123';
You can't use brew install to upgrade an installed formula. If you want upgrade all of outdated formulas, you can use the command below.
brew outdated | xargs brew upgrade
CSS properties should be set by cssText
property or setAttribute
method.
// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");
Styles should not be set by assigning a string directly to the style
property (as in elt.style = "color: blue;"
), since it is considered read-only, as the style
attribute returns a CSSStyleDeclaration
object which is also read-only.
There is a comment by @afr0 asking how to filter on folders..
There is two ways using the GetDirectoryReference
or looping through a containers blobs and checking the type. The code below is in C#
CloudBlobContainer container = blobClient.GetContainerReference("photos");
//Method 1. grab a folder reference directly from the container
CloudBlobDirectory folder = container.GetDirectoryReference("directoryName");
//Method 2. Loop over container and grab folders.
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
if (item.GetType() == typeof(CloudBlobDirectory))
{
// we know this is a sub directory now
CloudBlobDirectory subFolder = (CloudBlobDirectory)item;
Console.WriteLine("Directory: {0}", subFolder.Uri);
}
}
read this for more in depth coverage: http://www.codeproject.com/Articles/297052/Azure-Storage-Blobs-Service-Working-with-Directori
None of the previously given examples were meeting my needs completely, so I wrote my own queue that allows following functionality: iteration, index access, indexOf, lastIndexOf, get first, get last, offer, remaining capacity, expand capacity, dequeue last, dequeue first, enqueue / add element, dequeue / remove element, subQueueCopy, subArrayCopy, toArray, snapshot, basics like size, remove or contains.
Include <ctime>
and use the time
function.
Probably the project you are running is not compatible (API version/Hardware requirements) with the emulator settings. Check in your build.gradle
file if the targetSDK and minimumSdk version is lower or equal to the sdk version of your Emulator.
You should also uncheck Tools > Android > Enable ADB Integration
If your case is different then restart your Android Studio and run the emulator again.
The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.
See also here: How to supply value to an annotation from a Constant java
It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.
Try using private browsing in Safari or deleting your entire cache/cookies.
I've had some similar issues using chrome when the browser thought it had the website in its cache but actually had not.
The part of the http request that makes the server respond a 304 is the etag. Seems like Safari is sending the right etag without having the corresponding cache.
If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:
interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim
You also can set the width of a audio tag by JavaScript:
audio = document.getElementById('audio-id');
audio.style.width = '200px';
As you are in python3 , use dict.items()
instead of dict.iteritems()
iteritems()
was removed in python3, so you can't use this method anymore.
Take a look at Python 3.0 Wiki Built-in Changes section, where it is stated:
Removed
dict.iteritems()
,dict.iterkeys()
, anddict.itervalues()
.Instead: use
dict.items()
,dict.keys()
, anddict.values()
respectively.
You can simply use outerHTML property over the element. It will return what you desire.
Let's create a function named get_string(element)
var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));
function get_string(element) {
console.log(element.outerHTML);
}
get_string(el); // your desired output
_x000D_
i use this way, don't forget to put your css file on public folder.
for example i put my bootstrap css on
"root/public/bootstrap/css/bootstrap.min.css"
to access from header:
<link href="{{ asset('bootstrap/css/bootstrap.min.css') }}" rel="stylesheet" type="text/css" >
hope this help
In software engineering, multi-tier architecture (often referred to as n-tier architecture) is a client-server architecture in which, the presentation, the application processing and the data management are logically separate processes. For example, an application that uses middleware to service data requests between a user and a database employs multi-tier architecture. The most widespread use of "multi-tier architecture" refers to three-tier architecture.
It's debatable what counts as "tiers," but in my opinion it needs to at least cross the process boundary. Or else it's called layers. But, it does not need to be in physically different machines. Although I don't recommend it, you can host logical tier and database on the same box.
Edit: One implication is that presentation tier and the logic tier (sometimes called Business Logic Layer) needs to cross machine boundaries "across the wire" sometimes over unreliable, slow, and/or insecure network. This is very different from simple Desktop application where the data lives on the same machine as files or Web Application where you can hit the database directly.
For n-tier programming, you need to package up the data in some sort of transportable form called "dataset" and fly them over the wire. .NET's DataSet class or Web Services protocol like SOAP are few of such attempts to fly objects over the wire.
Unless the array is sorted, that's the best you're going to get. If it is sorted, just take the first and last elements.
Of course, if it's not sorted, then sorting first and grabbing the first and last is guaranteed to be less efficient than just looping through once. Even the best sorting algorithms have to look at each element more than once (an average of O(log N) times for each element. That's O(N*Log N) total. A simple scan once through is only O(N).
If you are wanting quick access to the largest element in a data structure, take a look at heaps for an efficient way to keep objects in some sort of order.
what about this?
$(this).mouseleave(function(){
var thisUI = $(this);
$('html').click(function(){
thisUI.hide();
$('html').unbind('click');
});
});
When you are using a virtualenv
, you can specify a requirements.txt
file to install all the dependencies.
A typical usage:
$ pip install -r requirements.txt
The packages need to be in a specific format for pip
to understand, which is
feedparser==5.1.3
wsgiref==0.1.2
django==1.4.2
...
That is the "requirements format".
Here, django==1.4.2
implies install django
version 1.4.2
(even though the latest is 1.6.x).
If you do not specify ==1.4.2
, the latest version available would be installed.
You can read more in "Virtualenv and pip Basics", and the official "Requirements File Format" documentation.
Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE
in your AndroidManifest.xml for this to work.
_ how could I have found myself the information I needed in the online documentation?
You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.
string sample = "ratty";
Console.WriteLine(sample[0]);
And
Console.WriteLine(sample.Chars(0));
Reference: http://msdn.microsoft.com/en-us/library/system.string.chars%28v=VS.71%29.aspx
The above is same as using indexers in c#.
Found out these problems can be addressed by using
ObjectMapper#convertValue(Object fromValue, Class<T> toValueType)
As a result, the origal quuestion can be solved in a 2-step converison:
Demarshall the JSON back to an object - in which the Map<String, Object>
is demarshalled as a HashMap<String, LinkedHashMap>
, by using bjectMapper#readValue().
Convert inner LinkedHashMaps back to proper objects
ObjectMapper mapper = new ObjectMapper();
Class clazz = (Class) Class.forName(classType);
MyOwnObject value = mapper.convertValue(value, clazz);
To prevent the 'classType' has to be known in advance, I enforced during marshalling an extra Map was added, containing <key, classNameString>
pairs. So at unmarshalling time, the classType can be extracted dynamically.
I believe you're looking for the @filename
syntax, e.g.:
strip new lines
curl --data "@/path/to/filename" http://...
keep new lines
curl --data-binary "@/path/to/filename" http://...
curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary
in place of --data
Just to add to others, a note specific to forking.
It's good to realize that technically, cloning the repo and forking the repo are the same thing. Do:
git clone $some_other_repo
and you can tap yourself on the back---you have just forked some other repo.
Git, as a VCS, is in fact all about cloning forking. Apart from "just browsing" using remote UI such as cgit, there is very little to do with git repo that does not involve forking cloning the repo at some point.
However,
when someone says I forked repo X, they mean that they have created a clone of the repo somewhere else with intention to expose it to others, for example to show some experiments, or to apply different access control mechanism (eg. to allow people without Github access but with company internal account to collaborate).
Facts that: the repo is most probably created with other command than
git clone
, that it's most probably hosted somewhere on a server as
opposed to somebody's laptop, and most probably has slightly different
format (it's a "bare repo", ie. without working tree) are all just
technical details.
The fact that it will most probably contain different set of branches, tags or commits is most probably the reason why they did it in the first place.
(What Github does when you click "fork", is just cloning with added sugar: it clones the repo for you, puts it under your account, records the "forked from" somewhere, adds remote named "upstream", and most importantly, plays the nice animation.)
When someone says I cloned repo X, they mean that they have created a clone of the repo locally on their laptop or desktop with intention study it, play with it, contribute to it, or build something from source code in it.
The beauty of Git is that it makes this all perfectly fit together: all these repos share the common part of block commit chain so it's possible to safely (see note below) merge changes back and forth between all these repos as you see fit.
Note: "safely" as long as you don't rewrite the common part of the chain, and as long as the changes are not conflicting.
Have you tried simply using the media attribute for you css reference?
<link rel="stylesheet" href="css/style2.css" media="print" type="text/css" />
Or set it to screen if you don't want the printed version to use the style:
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
This way you don't need to add it dynamically.
Python script:
import re
text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)
Output:
text1
text2
text3
text4
text5
text6
Test this code here.
Input ("Remove Quotes.cmd" "This is a Test")
@ECHO OFF
REM Set "string" variable to "first" command line parameter
SET STRING=%1
REM Remove Quotes [Only Remove Quotes if NOT Null]
IF DEFINED STRING SET STRING=%STRING:"=%
REM IF %1 [or String] is NULL GOTO MyLabel
IF NOT DEFINED STRING GOTO MyLabel
REM OR IF "." equals "." GOTO MyLabel
IF "%STRING%." == "." GOTO MyLabel
REM GOTO End of File
GOTO :EOF
:MyLabel
ECHO Welcome!
PAUSE
Output (There is none, %1 was NOT blank, empty, or NULL):
Run ("Remove Quotes.cmd") without any parameters with the above script 1
Output (%1 is blank, empty, or NULL):
Welcome!
Press any key to continue . . .
Note: If you set a variable inside an IF ( ) ELSE ( )
statement, it will not be available to DEFINED until after it exits the "IF" statement (unless "Delayed Variable Expansion" is enabled; once enabled use an exclamation mark "!" in place of the percent "%" symbol}.
For example:
Input ("Remove Quotes.cmd" "This is a Test")
@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET STRING=%0
IF 1==1 (
SET STRING=%1
ECHO String in IF Statement='%STRING%'
ECHO String in IF Statement [delayed expansion]='!STRING!'
)
ECHO String out of IF Statement='%STRING%'
REM Remove Quotes [Only Remove Quotes if NOT Null]
IF DEFINED STRING SET STRING=%STRING:"=%
ECHO String without Quotes=%STRING%
REM IF %1 is NULL GOTO MyLabel
IF NOT DEFINED STRING GOTO MyLabel
REM GOTO End of File
GOTO :EOF
:MyLabel
ECHO Welcome!
ENDLOCAL
PAUSE
Output:
C:\Users\Test>"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd" "This is a Test"
String in IF Statement='"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"'
String in IF Statement [delayed expansion]='"This is a Test"'
String out of IF Statement='"This is a Test"'
String without Quotes=This is a Test
C:\Users\Test>
Note: It will also remove quotes from inside the string.
For Example (using script 1 or 2): C:\Users\Test\Documents\Batch Files>"Remove Quotes.cmd" "This is "a" Test"
Output (Script 2):
String in IF Statement='"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"'
String in IF Statement [delayed expansion]='"This is "a" Test"'
String out of IF Statement='"This is "a" Test"'
String without Quotes=This is a Test
Execute ("Remove Quotes.cmd") without any parameters in Script 2:
Output:
Welcome!
Press any key to continue . . .
=$W$4<=TODAY()
Returns true for dates up to and including today, false otherwise.
import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
or use lambda
sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)
If you have a POSIX-2008 compliant system (any modern Linux), you can use the safe and convenient asprintf()
function: It will malloc()
enough memory for you, you don't need to worry about the maximum string size. Use it like this:
char* string;
if(0 > asprintf(&string, "Formatting a number: %d\n", 42)) return error;
log_out(string);
free(string);
This is the minimum effort you can get to construct the string in a secure fashion. The sprintf()
code you gave in the question is deeply flawed:
There is no allocated memory behind the pointer. You are writing the string to a random location in memory!
Even if you had written
char s[42];
you would be in deep trouble, because you can't know what number to put into the brackets.
Even if you had used the "safe" variant snprintf()
, you would still run the danger that your strings gets truncated. When writing to a log file, that is a relatively minor concern, but it has the potential to cut off precisely the information that would have been useful. Also, it'll cut off the trailing endline character, gluing the next log line to the end of your unsuccessfully written line.
If you try to use a combination of malloc()
and snprintf()
to produce correct behavior in all cases, you end up with roughly twice as much code than I have given for asprintf()
, and basically reprogram the functionality of asprintf()
.
If you are looking at providing a wrapper of log_out()
that can take a printf()
style parameter list itself, you can use the variant vasprintf()
which takes a va_list
as an argument. Here is a perfectly safe implementation of such a wrapper:
//Tell gcc that we are defining a printf-style function so that it can do type checking.
//Obviously, this should go into a header.
void log_out_wrapper(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
void log_out_wrapper(const char *format, ...) {
char* string;
va_list args;
va_start(args, format);
if(0 > vasprintf(&string, format, args)) string = NULL; //this is for logging, so failed allocation is not fatal
va_end(args);
if(string) {
log_out(string);
free(string);
} else {
log_out("Error while logging a message: Memory allocation failed.\n");
}
}
EF 4.7 actually gives a hint when you run Enable-migrations at multiple context.
More than one context type was found in the assembly 'Service.Domain'.
To enable migrations for 'Service.Domain.DatabaseContext.Context1',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context1.
To enable migrations for 'Service.Domain.DatabaseContext.Context2',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context2.
Another design pattern that I have seen involves using blocks, which is especially useful when a method is being run asynchronously.
Say we have the following error codes defined:
typedef NS_ENUM(NSInteger, MyErrorCodes) {
MyErrorCodesEmptyString = 500,
MyErrorCodesInvalidURL,
MyErrorCodesUnableToReachHost,
};
You would define your method that can raise an error like so:
- (void)getContentsOfURL:(NSString *)path success:(void(^)(NSString *html))success failure:(void(^)(NSError *error))failure {
if (path.length == 0) {
if (failure) {
failure([NSError errorWithDomain:@"com.example" code:MyErrorCodesEmptyString userInfo:nil]);
}
return;
}
NSString *htmlContents = @"";
// Exercise for the reader: get the contents at that URL or raise another error.
if (success) {
success(htmlContents);
}
}
And then when you call it, you don't need to worry about declaring the NSError object (code completion will do it for you), or checking the returning value. You can just supply two blocks: one that will get called when there is an exception, and one that gets called when it succeeds:
[self getContentsOfURL:@"http://google.com" success:^(NSString *html) {
NSLog(@"Contents: %@", html);
} failure:^(NSError *error) {
NSLog(@"Failed to get contents: %@", error);
if (error.code == MyErrorCodesEmptyString) { // make sure to check the domain too
NSLog(@"You must provide a non-empty string");
}
}];
If you want to be able to return to the precise version of the repository at the time you do a build it is best to tag the commit from which you make the build.
The other answers provide techniques to return the repository to the most recent commit in a branch as of a certain time-- but they might not always suffice. For example, if you build from a branch, and later delete the branch, or build from a branch that is later rebased, the commit you built from can become "unreachable" in git from any current branch. Unreachable objects in git may eventually be removed when the repository is compacted.
Putting a tag on the commit means it never becomes unreachable, no matter what you do with branches afterwards (barring removing the tag).
You must dereference the iterator in order to retrieve the member of your set.
std::set<unsigned long>::iterator it;
for (it = SERVER_IPS.begin(); it != SERVER_IPS.end(); ++it) {
u_long f = *it; // Note the "*" here
}
If you have C++11 features, you can use a range-based for loop:
for(auto f : SERVER_IPS) {
// use f here
}
Try adding return false;
in your click callback like this -
$(document).ready(function() {
$('.popup').click(function(event) {
window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
return false;
});
});
The problem is, you need a xsd schema for packages.config
.
This is how you can create a schema (I found it here):
Open your Config file -> XML -> Create Schema
This would create a packages.xsd
for you, and opens it in Visual Studio:
In my case, packages.xsd
was created under this path:
C:\Users\MyUserName\AppData\Local\Temp
Now I don't want to reference the packages.xsd
from a Temp folder, but I want it to be added to my solution and added to source control, so other users can get it... so I copied packages.xsd
and pasted it into my solution folder. Then I added the file to my solution:
1. Copy packages.xsd
in the same folder as your solution
2. From VS, right click on solution -> Add -> Existing Item... and then add packages.xsd
So, now we have created packages.xsd
and added it to the Solution. All we need to do is to tell the config file to use this schema.
Open the config file, then from the top menu select:
XML -> Schemas...
Add your packages.xsd
, and select Use this schema (see below)
To see where the data directory is, use this query.
show data_directory;
To see all the run-time parameters, use
show all;
You can create tablespaces to store database objects in other parts of the filesystem. To see tablespaces, which might not be in that data directory, use this query.
SELECT * FROM pg_tablespace;
I suggest use the common way of import.
First I will explain the way it called "relative import" maybe this way cause of some error
Second I will explain the common way of import.
FIRST:
In go version >= 1.12 there is some new tips about import file and somethings changed.
1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"
2- You have to use uppercase when you want to import a file!
3- Use Uppercase for variables, structures and functions that you want to import in another files
Notice: There is no way to import the main.go in another file.
file directory is:
root
|_____main.go
|_____model
|_____example.go
this is a example.go:
package model
import (
"time"
)
var StartTime = time.Now()
and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase
package main
import (
Mod "./model"
"fmt"
)
func main() {
fmt.Println(Mod.StartTime)
}
NOTE!!!
NOTE: I don't recommend this this type of import!
SECOND:
(normal import)
the better way import file is:
your structure should be like this:
root
|_____github.com
|_________Your-account-name-in-github
| |__________Your-project-name
| |________main.go
| |________handlers
| |________models
|
|_________gorilla
|__________sessions
and this is a example:
package main
import (
"github.com/gorilla/sessions"
)
func main(){
//you can use sessions here
}
so you can import "github.com/gorilla/sessions" in every where that you want...just import it.
I found a great code for you:
HTML
<form class="form-wrapper cf">
<input type="text" placeholder="Search here..." required>
<button type="submit">Search</button>
</form>
CSS
/*Clearing Floats*/
.cf:before, .cf:after {
content:"";
display:table;
}
.cf:after {
clear:both;
}
.cf {
zoom:1;
}
/* Form wrapper styling */
.form-wrapper {
width: 450px;
padding: 15px;
margin: 150px auto 50px auto;
background: #444;
background: rgba(0,0,0,.2);
border-radius: 10px;
box-shadow: 0 1px 1px rgba(0,0,0,.4) inset, 0 1px 0 rgba(255,255,255,.2);
}
/* Form text input */
.form-wrapper input {
width: 330px;
height: 20px;
padding: 10px 5px;
float: left;
font: bold 15px 'lucida sans', 'trebuchet MS', 'Tahoma';
border: 0;
background: #eee;
border-radius: 3px 0 0 3px;
}
.form-wrapper input:focus {
outline: 0;
background: #fff;
box-shadow: 0 0 2px rgba(0,0,0,.8) inset;
}
.form-wrapper input::-webkit-input-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
.form-wrapper input:-moz-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
.form-wrapper input:-ms-input-placeholder {
color: #999;
font-weight: normal;
font-style: italic;
}
/* Form submit button */
.form-wrapper button {
overflow: visible;
position: relative;
float: right;
border: 0;
padding: 0;
cursor: pointer;
height: 40px;
width: 110px;
font: bold 15px/40px 'lucida sans', 'trebuchet MS', 'Tahoma';
color: #fff;
text-transform: uppercase;
background: #d83c3c;
border-radius: 0 3px 3px 0;
text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);
}
.form-wrapper button:hover {
background: #e54040;
}
.form-wrapper button:active,
.form-wrapper button:focus {
background: #c42f2f;
outline: 0;
}
.form-wrapper button:before { /* left arrow */
content: '';
position: absolute;
border-width: 8px 8px 8px 0;
border-style: solid solid solid none;
border-color: transparent #d83c3c transparent;
top: 12px;
left: -6px;
}
.form-wrapper button:hover:before {
border-right-color: #e54040;
}
.form-wrapper button:focus:before,
.form-wrapper button:active:before {
border-right-color: #c42f2f;
}
.form-wrapper button::-moz-focus-inner { /* remove extra button spacing for Mozilla Firefox */
border: 0;
padding: 0;
}
For macOs users you can use Homebrew instead :
# For php v7.0
brew install [email protected]
# For php v7.1
brew install [email protected]
# For php v7.2
brew install [email protected]
# For php v7.3
brew install [email protected]
# For php v7.4
brew install [email protected]
The selected answer works, but it could use some improvement.
My solution relies on the creation of an OPTIONS variable that defines all of the options and their defaults. OPTIONS is also used to test whether a supplied option is valid. A tremendous amount of code is saved by simply storing the option values in variables named the same as the option. The amount of code is constant regardless of how many options are defined; only the OPTIONS definition has to change.
EDIT - Also, the :loop code must change if the number of mandatory positional arguments changes. For example, often times all arguments are named, in which case you want to parse arguments beginning at position 1 instead of 3. So within the :loop, all 3 become 1, and 4 becomes 2.
@echo off
setlocal enableDelayedExpansion
:: Define the option names along with default values, using a <space>
:: delimiter between options. I'm using some generic option names, but
:: normally each option would have a meaningful name.
::
:: Each option has the format -name:[default]
::
:: The option names are NOT case sensitive.
::
:: Options that have a default value expect the subsequent command line
:: argument to contain the value. If the option is not provided then the
:: option is set to the default. If the default contains spaces, contains
:: special characters, or starts with a colon, then it should be enclosed
:: within double quotes. The default can be undefined by specifying the
:: default as empty quotes "".
:: NOTE - defaults cannot contain * or ? with this solution.
::
:: Options that are specified without any default value are simply flags
:: that are either defined or undefined. All flags start out undefined by
:: default and become defined if the option is supplied.
::
:: The order of the definitions is not important.
::
set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"
:: Set the default option values
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
:: Validate and store the options, one at a time, using a loop.
:: Options start at arg 3 in this example. Each SHIFT is done starting at
:: the first option so required args are preserved.
::
if not "%~3"=="" (
set "test=!options:*%~3:=! "
if "!test!"=="!options! " (
rem No substitution was made so this is an invalid option.
rem Error handling goes here.
rem I will simply echo an error message.
echo Error: Invalid option %~3
) else if "!test:~0,1!"==" " (
rem Set the flag option using the option name.
rem The value doesn't matter, it just needs to be defined.
set "%~3=1"
) else (
rem Set the option value using the option as the name.
rem and the next arg as the value
set "%~3=%~4"
shift /3
)
shift /3
goto :loop
)
:: Now all supplied options are stored in variables whose names are the
:: option names. Missing options have the default value, or are undefined if
:: there is no default.
:: The required args are still available in %1 and %2 (and %0 is also preserved)
:: For this example I will simply echo all the option values,
:: assuming any variable starting with - is an option.
::
set -
:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!
There really isn't that much code. Most of the code above is comments. Here is the exact same code, without the comments.
@echo off
setlocal enableDelayedExpansion
set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
set "test=!options:*%~3:=! "
if "!test!"=="!options! " (
echo Error: Invalid option %~3
) else if "!test:~0,1!"==" " (
set "%~3=1"
) else (
set "%~3=%~4"
shift /3
)
shift /3
goto :loop
)
set -
:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!
This solution provides Unix style arguments within a Windows batch. This is not the norm for Windows - batch usually has the options preceding the required arguments and the options are prefixed with /
.
The techniques used in this solution are easily adapted for a Windows style of options.
%1
, and it continues until arg 1 does not begin with /
/
.SET /VAR=VALUE
failsSET "/VAR=VALUE"
works. I am already doing this in my solution anyway./
. This limitation can be eliminated by employing an implicitly defined //
option that serves as a signal to exit the option parsing loop. Nothing would be stored for the //
"option".
Update 2015-12-28: Support for !
in option values
In the code above, each argument is expanded while delayed expansion is enabled, which means that !
are most likely stripped, or else something like !var!
is expanded. In addition, ^
can also be stripped if !
is present. The following small modification to the un-commented code removes the limitation such that !
and ^
are preserved in option values.
@echo off
setlocal enableDelayedExpansion
set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
set "test=!options:*%~3:=! "
if "!test!"=="!options! " (
echo Error: Invalid option %~3
) else if "!test:~0,1!"==" " (
set "%~3=1"
) else (
setlocal disableDelayedExpansion
set "val=%~4"
call :escapeVal
setlocal enableDelayedExpansion
for /f delims^=^ eol^= %%A in ("!val!") do endlocal&endlocal&set "%~3=%%A" !
shift /3
)
shift /3
goto :loop
)
goto :endArgs
:escapeVal
set "val=%val:^=^^%"
set "val=%val:!=^!%"
exit /b
:endArgs
set -
:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!
lid -g groupname | cut -f1 -d'('
ref means that the value in the ref parameter is already set, the method can read and modify it. Using the ref keyword is the same as saying that the caller is responsible for initializing the value of the parameter.
out tells the compiler that the initialization of object is the responsibility of the function, the function has to assign to the out parameter. It's not allowed to leave it unassigned.
We do a lot of work where we need to figure out which IP's are within certain subnets. I've found that the simplest and most reliable way to do this is:
ALTER FUNCTION [dbo].[IP_To_INT ]
(
@IP CHAR(15)
)
RETURNS BIGINT
AS
BEGIN
DECLARE @IntAns BIGINT,
@block1 BIGINT,
@block2 BIGINT,
@block3 BIGINT,
@block4 BIGINT,
@base BIGINT
SELECT
@block1 = CONVERT(BIGINT, PARSENAME(@IP, 4)),
@block2 = CONVERT(BIGINT, PARSENAME(@IP, 3)),
@block3 = CONVERT(BIGINT, PARSENAME(@IP, 2)),
@block4 = CONVERT(BIGINT, PARSENAME(@IP, 1))
IF (@block1 BETWEEN 0 AND 255)
AND (@block2 BETWEEN 0 AND 255)
AND (@block3 BETWEEN 0 AND 255)
AND (@block4 BETWEEN 0 AND 255)
BEGIN
SET @base = CONVERT(BIGINT, @block1 * 16777216)
SET @IntAns = @base +
(@block2 * 65536) +
(@block3 * 256) +
(@block4)
END
ELSE
SET @IntAns = -1
RETURN @IntAns
END
I could not really work with the above. So this might help someone.
$http.get(url)
.then(
function(response) {
console.log('get',response)
}
).catch(
function(response) {
console.log('return code: ' + response.status);
}
)
See also the $http response
parameter.
You'd probably use the subprocess module. Something like this:
import subprocess
p = subprocess.Popen(["scp", myfile, destination])
sts = os.waitpid(p.pid, 0)
Where destination
is probably of the form user@remotehost:remotepath
. Thanks to
@Charles Duffy for pointing out the weakness in my original answer, which used a single string argument to specify the scp operation shell=True
- that wouldn't handle whitespace in paths.
The module documentation has examples of error checking that you may want to perform in conjunction with this operation.
Ensure that you've set up proper credentials so that you can perform an unattended, passwordless scp between the machines. There is a stackoverflow question for this already.
For swift
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
++notificationNumber
application.applicationIconBadgeNumber = notificationNumber;
if let aps = userInfo["aps"] as? NSDictionary {
var message = aps["alert"]
println("my messages : \(message)")
}
}
Another way to dump data as file from table by DumpDataFromTable sproc
EXEC dbo.DumpDataFromTable
@SchemaName = 'dbo'
,@TableName = 'YourTableName'
,@PathOut = N'c:\tmp\scripts\' -- folder must exist !!!'
Note: SQL must have permission to create files, if is not set-up then exec follow line once
EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
By this script you can call the sproc: DumpDataFromTable.sql and dump more tables in one go, instead of doing manually one by one from Management Studio
By default the format of generated scrip will be like
INSERT INTO <TableName> SELECT <Values>
Or you can change the generated format into
SELECT ... FROM
by setting variable @BuildMethod = 2
full sproc code:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DumpDataFromTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE dbo.[DumpDataFromTable]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Oleg Ciobanu
-- Create date: 20171214
-- Version 1.02
-- Description:
-- dump data in 2 formats
-- @BuildMethod = 1 INSERT INTO format
-- @BuildMethod = 2 SELECT * FROM format
--
-- SQL must have permission to create files, if is not set-up then exec follow line once
-- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
--
-- =============================================
CREATE PROCEDURE [dbo].[DumpDataFromTable]
(
@SchemaName nvarchar(128) --= 'dbo'
,@TableName nvarchar(128) --= 'testTable'
,@WhereClause nvarchar (1000) = '' -- must start with AND
,@BuildMethod int = 1 -- taking values 1 for INSERT INTO forrmat or 2 for SELECT from value Table
,@PathOut nvarchar(250) = N'c:\tmp\scripts\' -- folder must exist !!!'
,@AsFileNAme nvarchar(250) = NULL -- if is passed then will use this value as FileName
,@DebugMode int = 0
)
AS
BEGIN
SET NOCOUNT ON;
-- run follow next line if you get permission deny for sp_OACreate,sp_OAMethod
-- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
DECLARE @Sql nvarchar (max)
DECLARE @SqlInsert nvarchar (max) = ''
DECLARE @Columns nvarchar(max)
DECLARE @ColumnsCast nvarchar(max)
-- cleanUp/prepraring data
SET @SchemaName = REPLACE(REPLACE(@SchemaName,'[',''),']','')
SET @TableName = REPLACE(REPLACE(@TableName,'[',''),']','')
SET @AsFileNAme = NULLIF(@AsFileNAme,'')
SET @AsFileNAme = REPLACE(@AsFileNAme,'.','_')
SET @AsFileNAme = COALESCE(@PathOut + @AsFileNAme + '.sql', @PathOut + @SchemaName + ISNULL('_' + @TableName,N'') + '.sql')
--debug
IF @DebugMode = 1
PRINT @AsFileNAme
-- Create temp SP what will be responsable for generating script files
DECLARE @PRC_WritereadFile VARCHAR(max) =
'IF EXISTS (SELECT * FROM sys.objects WHERE type = ''P'' AND name = ''PRC_WritereadFile'')
BEGIN
DROP Procedure PRC_WritereadFile
END;'
EXEC (@PRC_WritereadFile)
-- '
SET @PRC_WritereadFile =
'CREATE Procedure PRC_WritereadFile (
@FileMode INT -- Recreate = 0 or Append Mode 1
,@Path NVARCHAR(1000)
,@AsFileNAme NVARCHAR(500)
,@FileBody NVARCHAR(MAX)
)
AS
DECLARE @OLEResult INT
DECLARE @FS INT
DECLARE @FileID INT
DECLARE @hr INT
DECLARE @FullFileName NVARCHAR(1500) = @Path + @AsFileNAme
-- Create Object
EXECUTE @OLEResult = sp_OACreate ''Scripting.FileSystemObject'', @FS OUTPUT
IF @OLEResult <> 0 BEGIN
PRINT ''Scripting.FileSystemObject''
GOTO Error_Handler
END
IF @FileMode = 0 BEGIN -- Create
EXECUTE @OLEResult = sp_OAMethod @FS,''CreateTextFile'',@FileID OUTPUT, @FullFileName
IF @OLEResult <> 0 BEGIN
PRINT ''CreateTextFile''
GOTO Error_Handler
END
END ELSE BEGIN -- Append
EXECUTE @OLEResult = sp_OAMethod @FS,''OpenTextFile'',@FileID OUTPUT, @FullFileName, 8, 0 -- 8- forappending
IF @OLEResult <> 0 BEGIN
PRINT ''OpenTextFile''
GOTO Error_Handler
END
END
EXECUTE @OLEResult = sp_OAMethod @FileID, ''WriteLine'', NULL, @FileBody
IF @OLEResult <> 0 BEGIN
PRINT ''WriteLine''
GOTO Error_Handler
END
EXECUTE @OLEResult = sp_OAMethod @FileID,''Close''
IF @OLEResult <> 0 BEGIN
PRINT ''Close''
GOTO Error_Handler
END
EXECUTE sp_OADestroy @FS
EXECUTE sp_OADestroy @FileID
GOTO Done
Error_Handler:
DECLARE @source varchar(30), @desc varchar (200)
EXEC @hr = sp_OAGetErrorInfo null, @source OUT, @desc OUT
PRINT ''*** ERROR ***''
SELECT OLEResult = @OLEResult, hr = CONVERT (binary(4), @hr), source = @source, description = @desc
Done:
';
-- '
EXEC (@PRC_WritereadFile)
EXEC PRC_WritereadFile 0 /*Create*/, '', @AsFileNAme, ''
;WITH steColumns AS (
SELECT
1 as rn,
c.ORDINAL_POSITION
,c.COLUMN_NAME as ColumnName
,c.DATA_TYPE as ColumnType
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE 1 = 1
AND c.TABLE_SCHEMA = @SchemaName
AND c.TABLE_NAME = @TableName
)
--SELECT *
SELECT
@ColumnsCast = ( SELECT
CASE WHEN ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
THEN
'convert(nvarchar(1001), s.[' + ColumnName + ']' + ' , 121) AS [' + ColumnName + '],'
--,convert(nvarchar, [DateTimeScriptApplied], 121) as [DateTimeScriptApplied]
ELSE
'CAST(s.[' + ColumnName + ']' + ' AS NVARCHAR(1001)) AS [' + ColumnName + '],'
END
as 'data()'
FROM
steColumns t2
WHERE 1 =1
AND t1.rn = t2.rn
FOR xml PATH('')
)
,@Columns = ( SELECT
'[' + ColumnName + '],' as 'data()'
FROM
steColumns t2
WHERE 1 =1
AND t1.rn = t2.rn
FOR xml PATH('')
)
FROM steColumns t1
-- remove last char
IF lEN(@Columns) > 0 BEGIN
SET @Columns = SUBSTRING(@Columns, 1, LEN(@Columns)-1);
SET @ColumnsCast = SUBSTRING(@ColumnsCast, 1, LEN(@ColumnsCast)-1);
END
-- debug
IF @DebugMode = 1 BEGIN
print @ColumnsCast
print @Columns
select @ColumnsCast , @Columns
END
-- build unpivoted Data
SET @SQL = '
SELECT
u.rn
, c.ORDINAL_POSITION as ColumnPosition
, c.DATA_TYPE as ColumnType
, u.ColumnName
, u.ColumnValue
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn,
'
+ CHAR(13) + @ColumnsCast
+ CHAR(13) + 'FROM [' + @SchemaName + '].[' + @TableName + '] s'
+ CHAR(13) + 'WHERE 1 = 1'
+ CHAR(13) + COALESCE(@WhereClause,'')
+ CHAR(13) + ') tt
UNPIVOT
(
ColumnValue
FOR ColumnName in (
' + CHAR(13) + @Columns
+ CHAR(13)
+ '
)
) u
LEFT JOIN INFORMATION_SCHEMA.COLUMNS c ON c.COLUMN_NAME = u.ColumnName
AND c.TABLE_SCHEMA = '''+ @SchemaName + '''
AND c.TABLE_NAME = ''' + @TableName +'''
ORDER BY u.rn
, c.ORDINAL_POSITION
'
-- debug
IF @DebugMode = 1 BEGIN
print @Sql
exec (@Sql)
END
-- prepare data for cursor
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
DROP TABLE #tmp
CREATE TABLE #tmp
(
rn bigint
,ColumnPosition int
,ColumnType varchar (128)
,ColumnName varchar (128)
,ColumnValue nvarchar (2000) -- I hope this size will be enough for storring values
)
SET @Sql = 'INSERT INTO #tmp ' + CHAR(13) + @Sql
-- debug
IF @DebugMode = 1 BEGIN
print @Sql
END
EXEC (@Sql)
-- Insert dummy rec, otherwise will not proceed the last rec :)
INSERT INTO #tmp (rn)
SELECT MAX(rn) + 1
FROM #tmp
IF @DebugMode = 1 BEGIN
SELECT * FROM #tmp
END
DECLARE @rn bigint
,@ColumnPosition int
,@ColumnType varchar (128)
,@ColumnName varchar (128)
,@ColumnValue nvarchar (2000)
,@i int = -1 -- counter/flag
,@ColumnsInsert varchar(max) = NULL
,@ValuesInsert nvarchar(max) = NULL
DECLARE cur CURSOR FOR
SELECT rn, ColumnPosition, ColumnType, ColumnName, ColumnValue
FROM #tmp
ORDER BY rn, ColumnPosition -- note order is really important !!!
OPEN cur
FETCH NEXT FROM cur
INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue
IF @BuildMethod = 1
BEGIN
SET @SqlInsert = 'SET NOCOUNT ON;' + CHAR(13);
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileName, @SqlInsert
SET @SqlInsert = ''
END
ELSE BEGIN
SET @SqlInsert = 'SET NOCOUNT ON;' + CHAR(13);
SET @SqlInsert = @SqlInsert
+ 'SELECT *'
+ CHAR(13) + 'FROM ('
+ CHAR(13) + 'VALUES'
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileName, @SqlInsert
SET @SqlInsert = NULL
END
SET @i = @rn
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@i <> @rn) -- is a new row
BEGIN
IF @BuildMethod = 1
-- build as INSERT INTO -- as Default
BEGIN
SET @SqlInsert = 'INSERT INTO [' + @SchemaName + '].[' + @TableName + '] ('
+ CHAR(13) + @ColumnsInsert + ')'
+ CHAR(13) + 'VALUES ('
+ @ValuesInsert
+ CHAR(13) + ');'
END
ELSE
BEGIN
-- build as Table select
IF (@i <> @rn) -- is a new row
BEGIN
SET @SqlInsert = COALESCE(@SqlInsert + ',','') + '(' + @ValuesInsert+ ')'
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
SET @SqlInsert = '' -- in method 2 we should clear script
END
END
-- debug
IF @DebugMode = 1
print @SqlInsert
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
-- we have new row
-- initialise variables
SET @i = @rn
SET @ColumnsInsert = NULL
SET @ValuesInsert = NULL
END
-- build insert values
IF (@i = @rn) -- is same row
BEGIN
SET @ColumnsInsert = COALESCE(@ColumnsInsert + ',','') + '[' + @ColumnName + ']'
SET @ValuesInsert = CASE
-- date
--WHEN
-- @ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
--THEN
-- COALESCE(@ValuesInsert + ',','') + '''''' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''''''
-- numeric
WHEN
@ColumnType IN ('bit','tinyint','smallint','int','bigint'
,'money','real','','float','decimal','numeric','smallmoney')
THEN
COALESCE(@ValuesInsert + ',','') + '' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''
-- other types treat as string
ELSE
COALESCE(@ValuesInsert + ',','') + '''' + ISNULL(RTRIM(
-- escape single quote
REPLACE(@ColumnValue, '''', '''''')
),'NULL') + ''''
END
END
FETCH NEXT FROM cur
INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue
-- debug
IF @DebugMode = 1
BEGIN
print CAST(@rn AS VARCHAR) + '-' + CAST(@ColumnPosition AS VARCHAR)
END
END
CLOSE cur
DEALLOCATE cur
IF @BuildMethod = 1
BEGIN
PRINT 'ignore'
END
ELSE BEGIN
SET @SqlInsert = CHAR(13) + ') AS vtable '
+ CHAR(13) + ' (' + @Columns
+ CHAR(13) + ')'
EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
SET @SqlInsert = NULL
END
PRINT 'Done: ' + @AsFileNAme
END
Or can be downloaded latest version from https://github.com/Zindur/MSSQL-DumpTable/tree/master/Scripts
0755
= User:rwx
Group:r-x
World:r-x
0750
= User:rwx
Group:r-x
World:---
(i.e. World: no access)
r = read
w = write
x = execute (traverse for directories)
DO NOT use git push origin --mirror UNDER ALMOST ANY CIRCUMSTANCE.
It does not ask if you're sure you want to do this, and you'd better be sure, because it will erase all of your remote branches that are not on your local box.
OK - what you're missing is that its designed to be more industrial and serve many sites, so the config you want is probably:
/etc/apache2/sites-available/default
which on my system is linked to from /etc/apache2/sites-enabled/
if you want to have different sites with different options, copy the file and then change those...
Note that the %
syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:
instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)
This also fixes the error that you happened to have.
div{cursor: pointer; color:blue}_x000D_
_x000D_
p{cursor: text; color:red;}
_x000D_
<div> im Pointer cursor </div> _x000D_
<p> im Txst cursor </p>
_x000D_
You can try this method:
<h2 style="text-decoration: underline; text-underline-position: under; text-decoration-style: dotted">Hello World!</h2>
Please note that without text-underline-position: under;
you still will have a dotted underline but this property will give it more breathing space.
This is assuming you want to embed everything inside an HTML file using inline styling and not to use a separate CSS file or tag.
Calculates the best height of the image for available width.
import Foundation
public extension UIImage {
public func height(forWidth width: CGFloat) -> CGFloat {
let boundingRect = CGRect(
x: 0,
y: 0,
width: width,
height: CGFloat(MAXFLOAT)
)
let rect = AVMakeRect(
aspectRatio: size,
insideRect: boundingRect
)
return rect.size.height
}
}
string.find("substring")
will help you. This function returns -1
when there is no substring.
Simplest Understanding for default export
is
Export
is ES6's feature which is used to Export a module(file) and use it in some other module(file).
Default Export:
default export
is the convention if you want to export only one object(variable, function, class) from the file(module).Export or Named Export:
It is used to export the object(variable, function, calss) with the same name.
It is used to export multiple objects from one file.
It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as
operator.
In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.
You can configure the connect body parser middleware in a configuration block in your main application file:
/** Form Handling */
app.use(express.bodyParser({
uploadDir: '/tmp/uploads',
keepExtensions: true
}))
app.use(express.limit('5mb'));
No need to initialize an empty DataFrame (you weren't even doing that, you'd need pd.DataFrame()
with the parens).
Instead, to create a DataFrame where each series is a column,
series
, and df = pd.concat(series, axis=1)
Something like:
series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)
I think you forgot to change
data={this.props.data}
to
data={this.state.data}
in the render function of CommentBox. I did the same mistake when I was following the tutorial. Thus the whole render function should look like
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
instead of
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.props.data} />
<CommentForm />
</div>
);
Have you used the variable sum
anywhere else? That would explain it.
>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
The name sum
doesn't point to the function anymore now, it points to an integer.
Solution: Don't call your variable sum
, call it total
or something similar.
try this:
<div ng-if="$scope.length == 0" ? true : false></div>
and show or hide
<div ng-show="$scope.length == 0"></div>
else it will be hide
-----------------or--------------------------
if you are using $ctrl than code will be like this:
try this:
<div ng-if="$ctrl.length == 0" ? true : false></div>
and show or hide
<div ng-show="$ctrl.length == 0"></div>
else it will be hide
pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.
fscanf
will treat 2 arguments, and thus return 2. Your while statement will be false, hence never displaying what has been read, plus as it has read only 1 line, if is not at EOF, resulting in what you see.
Adding to @zzzzzzz answer, I ran the command:python3 -c "import sys; print(sys.path)"
and it provided me with different paths comparing to the same command with python
. The paths that were displayed with python3
were "python3 oriented".
See the output of the two different commands:
python -c "import sys; print(sys.path)"
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/local/lib/python2.7/dist-packages/setuptools-39.1.0-py2.7.egg', '/usr/lib/python2.7/dist-packages']
python3 -c "import sys; print(sys.path)"
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
Both commands were executed on my Ubuntu 18.04 machine.
arr[title] = link;
You're not pushing into the array, you're setting the element with the key title
to the value link
. As such your array should be an object.
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
Order of magnitude: zero.
In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.
The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.
Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.
Just in case you guys need it, Here a couple of links that can help you:
Cheers
Here is the example:
var charCode = "a".charCodeAt(0);_x000D_
console.log(charCode);
_x000D_
Or if you have longer strings:
var string = "Some string";_x000D_
_x000D_
for (var i = 0; i < string.length; i++) {_x000D_
console.log(string.charCodeAt(i));_x000D_
}
_x000D_
String.charCodeAt(x)
method will return ASCII character code at a given position.
Assuming you're referring to this plugin, your code should be:
// To Store
$(function() {
$.session.set("myVar", "value");
});
// To Read
$(function() {
alert($.session.get("myVar"));
});
Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown
file, which is displayed on the project page.
this step work perfectly for me.. you can try it
hope it work for you too. good luck
In jQuery 1.4 you get the $.isEmptyObject function, but if you are forced to use an older version of jQ like us poor Drupal developers just steal use this code:
// This is a function similar to the jQuery 1.4 $.isEmptyObject.
function isObjectEmpty(obj) {
for ( var name in obj ) {
return false;
}
return true;
}
Use it like:
console.log(isObjectEmpty(the_object)); // Returns true or false.
You can also do something like:
SELECT COUNT(DISTINCT id + name + address) FROM mytable
You can use your config.php file, and also use the power of helpers in CodeIgniter.
$config['header_css'] = array('style.css','prettyPhoto.css','nivo-slider.css');
$config['header_js'] = array('core.js','core.js',
'jquery-1.4.1.min.js',
'jquery-slidedeck.pack.lite.js',
'jquery-prettyPhoto.js',
'jquery.nivo.slider.js');
Source: https://jamshidhashimi.com/dynamically-add-javascript-and-css-files-in-codeigniter-header-page/
In memory usage and speed.
When you call jsonstr = json.dumps(mydata)
it first creates a full copy of your data in memory and only then you file.write(jsonstr)
it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.
When you call json.dump(mydata, file)
-- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.
Source: I checked the source code of json.dump()
and json.dumps()
and also tested both the variants measuring the time with time.time()
and watching the memory usage in htop.
@balalakshmi mentioned about the correct authentication settings. Authentication is only half of the problem, the other half is authorization.
If you're using Forms Authentication and standard controls like <asp:Login>
there are a couple of things you'll need to do to ensure that only your authenticated users can access secured pages.
In web.config
, under the <system.web>
section you'll need to disable anonymous access by default:
<authorization>
<deny users="?" />
</authorization>
Any pages that will be accessed anonymously (such as the Login.aspx page itself) will need to have an override that re-allows anonymous access. This requires a <location>
element and must be located at the <configuration>
level (outside the <system.web>
section), like this:
<!-- Anonymous files -->
<location path="Login.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Note that you'll also need to allow anonymous access to any style sheets or scripts that are used by the anonymous pages:
<!-- Anonymous folders -->
<location path="styles">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Be aware that the location's path
attribute is relative to the web.config
folder and cannot have a ~/
prefix, unlike most other path-type configuration attributes.
In my case nothing above has worked. After banging my head against the wall for a while I've found out, that I've destroyed the /etc/passwd
entries by running a custom-made-linux-server-setup-bash-script which worked well previously, but this time the regex within the "sed" command erased all the existing entries :D
After copy pasting the default entries from another working linux server I could finally restart sshd.
So don't forget to backup the original /etc/passwd
file before applying any regex replacements on it :)
Open a terminal, cd to the path of your Vagrantfile and write this
(Linux)
vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null
(OS X)
vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null | pbcopy
The command for Linux also works for windows. I have no way to test, sorry.
source: https://coderwall.com/p/etzdmq/get-vagrant-box-guest-ip-from-host
This is very useful to avoid errors when accessing properties of null or undefined objects.
null to undefined object
const obj = null;
const newObj = obj || undefined;
// newObj = undefined
undefined to empty object
const obj;
const newObj = obj || {};
// newObj = {}
// newObj.prop = undefined, but no error here
null to empty object
const obj = null;
const newObj = obj || {};
// newObj = {}
// newObj.prop = undefined, but no error here
Other answers here are correct: is
is used for identity comparison, while ==
is used for equality comparison. Since what you care about is equality (the two strings should contain the same characters), in this case the is
operator is simply wrong and you should be using ==
instead.
The reason is
works interactively is that (most) string literals are interned by default. From Wikipedia:
Interned strings speed up string comparisons, which are sometimes a performance bottleneck in applications (such as compilers and dynamic programming language runtimes) that rely heavily on hash tables with string keys. Without interning, checking that two different strings are equal involves examining every character of both strings. This is slow for several reasons: it is inherently O(n) in the length of the strings; it typically requires reads from several regions of memory, which take time; and the reads fills up the processor cache, meaning there is less cache available for other needs. With interned strings, a simple object identity test suffices after the original intern operation; this is typically implemented as a pointer equality test, normally just a single machine instruction with no memory reference at all.
So, when you have two string literals (words that are literally typed into your program source code, surrounded by quotation marks) in your program that have the same value, the Python compiler will automatically intern the strings, making them both stored at the same memory location. (Note that this doesn't always happen, and the rules for when this happens are quite convoluted, so please don't rely on this behavior in production code!)
Since in your interactive session both strings are actually stored in the same memory location, they have the same identity, so the is
operator works as expected. But if you construct a string by some other method (even if that string contains exactly the same characters), then the string may be equal, but it is not the same string -- that is, it has a different identity, because it is stored in a different place in memory.
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
An implicit cursor is one created "automatically" for you by Oracle when you execute a query. It is simpler to code, but suffers from
Example
SELECT col INTO var FROM table WHERE something;
An explicit cursor is one you create yourself. It takes more code, but gives more control - for example, you can just open-fetch-close if you only want the first record and don't care if there are others.
Example
DECLARE
CURSOR cur IS SELECT col FROM table WHERE something;
BEGIN
OPEN cur;
FETCH cur INTO var;
CLOSE cur;
END;
Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.
When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.
If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.
You can use <LinearLayout>
to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use.
Here is an example:
<LinearLayout
style="@style/FormItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="@style/FormLabel"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:text="@string/name_label"
/>
<EditText
style="@style/FormText.Editable"
android:id="@+id/cardholderName"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:hint="@string/card_name_hint"
android:imeOptions="actionNext"
android:singleLine="true"
/>
</LinearLayout>
Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
The embed URL for a channel's live stream is:
https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID
You can find your CHANNEL_ID at https://www.youtube.com/account_advanced
Page_Load happens after ViewState and PostData is sent into all of your server side controls by ASP.NET controls being created on the page. Page_Init is the event fired prior to ViewState and PostData being reinstated. Page_Load is where you typically do any page wide initilization. Page_PreRender is the last event you have a chance to handle prior to the page's state being rendered into HTML. Page_Load is the more typical event to work with.
How about this?
=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))
The "3" at the end means for column C.
I can't comment on @omega's comment because I don't have enough reputation but the answer to that question should be something like:
shake.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100" <!-- how long the animation lasts -->
android:fromDegrees="-5" <!-- how far to swing left -->
android:pivotX="50%" <!-- pivot from horizontal center -->
android:pivotY="50%" <!-- pivot from vertical center -->
android:repeatCount="10" <!-- how many times to swing back and forth -->
android:repeatMode="reverse" <!-- to make the animation go the other way -->
android:toDegrees="5" /> <!-- how far to swing right -->
Class.java
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
view.startAnimation(shake);
This is just one way of doing what you want, there may be better methods out there.
For Jackson 2.5 use :
@JsonInclude(content=Include.NON_NULL)
-l
(that's a lower-case L).
Sometimes you need to apply a function to the members of a list in place. The following code worked for me:
>>> def func(a, i):
... a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']
Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place
Same problem with me when I used this syntax problem solved.
Syntax:
Use [YourDatabaseName]
Your Query Here
Looks like you use %p: Print Pointers
Check this:
var minutesLabel = document.getElementById("minutes");_x000D_
var secondsLabel = document.getElementById("seconds");_x000D_
var totalSeconds = 0;_x000D_
setInterval(setTime, 1000);_x000D_
_x000D_
function setTime() {_x000D_
++totalSeconds;_x000D_
secondsLabel.innerHTML = pad(totalSeconds % 60);_x000D_
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));_x000D_
}_x000D_
_x000D_
function pad(val) {_x000D_
var valString = val + "";_x000D_
if (valString.length < 2) {_x000D_
return "0" + valString;_x000D_
} else {_x000D_
return valString;_x000D_
}_x000D_
}
_x000D_
<label id="minutes">00</label>:<label id="seconds">00</label>
_x000D_
Cast it as an int and subtract
$integer = (int)$your_number;
$decimal = $your_number - $integer;
Or just to get the decimal for comparison
$decimal = $your_number - (int)$your_number
It appears that you are extracting you certificate from the PKCS #12 key store and creating a new Java key store (with type "JKS"). You don't strictly have to provide a trust store password (although using one allows you to test the integrity of your root certificates).
So, try your program with only the following SSL properties set. The list shown in your question is over-specified and may be causing problems.
System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
Also, using the PKCS #12 file directly as the trust store should work, as long as the CA certificate is detected as a "trusted" entry. But in that case, you'll have to specify the javax.net.ssl.trustStoreType
property as "PKCS12"
too.
Try with these properties only. If you get the same error, I suspect your problem is not the key store. If it still occurs, post more of the stack trace in your question to narrow the problem down.
The new error, "the trustAnchors parameter must be non-empty," could be due to setting the javax.net.ssl.trustStore
property to a file that doesn't exist; if the file cannot be opened, an empty key store created, which would lead to this error.
import org.springframework.core.io.ClassPathResource;
...
File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();
It is worth noting that this will limit your deployment options, ClassPathResource.getFile()
only works if the container has exploded (unzipped) your war file.
Here is a sed solution:
sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt
To convert an object to a byte array:
// Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
You just need copy this function to your code and send to it the object that you need to convert to a byte array. If you need convert the byte array to an object again you can use the function below:
// Convert a byte array to an Object
public static Object ByteArrayToObject(byte[] arrBytes)
{
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = binForm.Deserialize(memStream);
return obj;
}
}
You can use these functions with custom classes. You just need add the [Serializable]
attribute in your class to enable serialization
put this line in OnCreate()
Context mcontext = this;
and them use this variable in following code
final AlertDialog.Builder alert = new AlertDialog.Builder(mcontext);
alert.setTitle(title);
alert.setMessage(description);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
Try this code.. It is running successfully..
TL;DR. In Visual Studio 2019
, when you add an Icon
resource to a Win32
(desktop) application you get an auto-generated icon file that has the formats below. I assume that the #1 developer tool for Windows does this right. Thus, a Windows
compatible should have the following formats:
| Resolution | Color depth | Format |
|:-----------|------------:|:------:|
| 256x256 | 32-bit | PNG |
| 64x64 | 32-bit | BMP |
| 48x48 | 32-bit | BMP |
| 32x32 | 32-bit | BMP |
| 16x16 | 32-bit | BMP |
| 48x48 | 8-bit | BMP |
| 32x32 | 8-bit | BMP |
| 16x16 | 8-bit | BMP |
Enter the following command to check if a private key and public key are a matched set (identical) or not a matched set (differ) in $USER/.ssh directory. The cut command prevents the comment at the end of the line in the public key from being compared, allowing only the key to be compared.
ssh-keygen -y -f ~/.ssh/id_rsa | diff -s - <(cut -d ' ' -f 1,2 ~/.ssh/id_rsa.pub)
Output will look like either one of these lines.
Files - and /dev/fd/63 are identical
Files - and /dev/fd/63 differ
I wrote a shell script that users use to check file permission of their ~/.ssh/files and matched key set. It solves my challenges with user incidents setting up ssh. It may help you. https://github.com/BradleyA/docker-security-infrastructure/tree/master/ssh
Note: My previous answer (in Mar 2018) no longer works with the latest releases of openssh. Previous answer: diff -qs <(ssh-keygen -yf ~/.ssh/id_rsa) <(cut -d ' ' -f 1,2 ~/.ssh/id_rsa.pub)
I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.
For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.
IsDbNull(int)
is usually much slower than using methods like GetSqlDateTime
and then comparing to DBNull.Value
. Try these extension methods for SqlDataReader
.
public static T Def<T>(this SqlDataReader r, int ord)
{
var t = r.GetSqlValue(ord);
if (t == DBNull.Value) return default(T);
return ((INullable)t).IsNull ? default(T) : (T)t;
}
public static T? Val<T>(this SqlDataReader r, int ord) where T:struct
{
var t = r.GetSqlValue(ord);
if (t == DBNull.Value) return null;
return ((INullable)t).IsNull ? (T?)null : (T)t;
}
public static T Ref<T>(this SqlDataReader r, int ord) where T : class
{
var t = r.GetSqlValue(ord);
if (t == DBNull.Value) return null;
return ((INullable)t).IsNull ? null : (T)t;
}
Use them like this:
var dd = r.Val<DateTime>(ords[4]);
var ii = r.Def<int>(ords[0]);
int nn = r.Def<int>(ords[0]);
The following class might come quite handy:
struct Error : std::exception
{
char text[1000];
Error(char const* fmt, ...) __attribute__((format(printf,2,3))) {
va_list ap;
va_start(ap, fmt);
vsnprintf(text, sizeof text, fmt, ap);
va_end(ap);
}
char const* what() const throw() { return text; }
};
Usage example:
throw Error("Could not load config file '%s'", configfile.c_str());
The aim of having the kernel support different ones is that you can try them out without a reboot; you can then run test workloads through the sytsem, measure performance, and then make that the standard one for your app.
On modern server-grade hardware, only the noop one appears to be at all useful. The others seem slower in my tests.
You can't stop a timer function mid-execution. You can only catch it after it completes and prevent it from triggering again.
@AlexanderMP's answer is correct, but you can also consider handling nulls with coalesce
:
declare @CodeNameString nvarchar(max)
set @CodeNameString = null
SELECT @CodeNameString = Coalesce(@CodeNameString + ', ', '') + cast(CodeName as varchar) from AccountCodes
select @CodeNameString
Here is my contribution, that deals with any URL using http or https, and use Promises.
const http = require('http')
const https = require('https')
const url = require('url')
function getHeaders(myURL) {
const parsedURL = url.parse(myURL)
const options = {
protocol: parsedURL.protocol,
hostname: parsedURL.hostname,
method: 'HEAD',
path: parsedURL.path
}
let protocolHandler = (parsedURL.protocol === 'https:' ? https : http)
return new Promise((resolve, reject) => {
let req = protocolHandler.request(options, (res) => {
resolve(res.headers)
})
req.on('error', (e) => {
reject(e)
})
req.end()
})
}
getHeaders(myURL).then((headers) => {
console.log(headers)
})
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
From Browser/Client perspective
JSP and JSF both looks same, As Per Application Requirements goes, JSP is more suited for request - response based applications.
JSF is targetted for richer event based Web applications. I see event as much more granular than request/response.
From Server Perspective
JSP page is converted to servlet, and it has only minimal behaviour.
JSF page is converted to components tree(by specialized FacesServlet) and it follows component lifecycle defined by spec.
Define state attributes. Add universal handleChange event handler. Add name param to input tag for mapping.
this.state = { stateAttrName:"" }
handleChange=(event)=>{
this.setState({[event.target.name]:event.target.value });
}
<input className="form-control" name="stateAttrName" value=
{this.state.stateAttrName} onChange={this.handleChange}/>
With a SimpleXml object, you can simply
$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
/* @var $xml SimpleXMLElement */
$domxml->loadXML($xml->asXML());
$domxml->save($newfile);
$xml
is your simplexml object
So then you simpleXml can be saved as a new file specified by $newfile
Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.
$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)
Change your maximum size,
label1.MaximumSize = new Size(100, 0);
And set your autosize to true.
label1.AutoSize = true;
That's it!
It sounds like your error comes from an attempt to run something like this (which works in Linux)
NODE_ENV=development node foo.js
the equivalent in Windows would be
SET NODE_ENV=development
node foo.js
running in the same command shell. You mentioned set NODE_ENV did not work, but wasn't clear how/when you executed it.
JavaScript is object-oriented, but it's radically different than other OOP languages like Java, C# or C++. Don't try to understand it like that. Throw that old knowledge out and start anew. JavaScript needs a different thinking.
I'd suggest to get a good manual or something on the subject. I myself found ExtJS Tutorials the best for me, although I haven't used the framework before or after reading it. But it does give a good explanation about what is what in JavaScript world. Sorry, it seems that that content has been removed. Here's a link to archive.org copy instead. Works today. :P
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
Like "Whisk" Said, the trick is in "AppendDataBoundItems" property
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.AppendDataBoundItems = true;
DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
DropDownList1.SelectedIndex = 0;
}
}
Thanks "Whisk"
In MySQL:
create table temp as select * from original_table
I know this is an old question but wouldn't the simple solution be to just protect the file at the OS level? Just prevent the users from accessing the file and then they shouldn't be able to touch it. This is just a guess and I'm not sure if this is an ideal solution.
I was having this issue when viewing my website on a phone. While I was trying to close the overlay, I was pretty much clicking on anything under the overlay. A solution that I found working for myself is to just add a
tag around the entire overlay
See ipdata.co a service I built that is fast and has reliable performance thanks to having 10 global endpoints each able to handle >10,000 requests per second!
This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.
This snippet will return the details of your current ip. To lookup other ip addresses, simply append the ip to the https://api.ipdata.co?api-key=test url eg.
https://api.ipdata.co/1.1.1.1?api-key=test
The API also provides an is_eu
field indicating whether the user is in an EU country.
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
$("#response").html(JSON.stringify(response, null, 4));_x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<pre id="response"></pre>
_x000D_
Here's the fiddle; https://jsfiddle.net/ipdata/6wtf0q4g/922/
I also wrote this detailed analysis of 8 of the best IP Geolocation APIs.
The main article in the Angular2 documentation on this subject is :
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child
It covers the following:
Pass data from parent to child with input binding
Intercept input property changes with a setter
Intercept input property changes with ngOnChanges
Parent listens for child event
Parent interacts with child via a local variable
Parent calls a ViewChild
Parent and children communicate via a service
check your casing, the name is typically stored in upper case
SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;
This happens because you trying to run service at the same port and there is an already running application.
This can happen because your service is not stopped in the process stack. Then you just have to kill this process.
There is no need to install anything here is the one line command to kill all running python processes.
for Linux based OS:
Bash:
kill -9 $(ps -A | grep python | awk '{print $1}')
Fish:
kill -9 (ps -A | grep python | awk '{print $1}')
A return value of the previously executed process.
10.4 Getting the return value of a program
In bash, the return value of a program is stored in a special variable called $?.
This illustrates how to capture the return value of a program, I assume that the directory dada does not exist. (This was also suggested by mike)
#!/bin/bash cd /dada &> /dev/null echo rv: $? cd $(pwd) &> /dev/null echo rv: $?
See Bash Programming Manual for more details.
If you just need a shortcut, then it is Ctrl + Q on Linux (and Windows). Just hover the mouse on the method and press Ctrl + Q to see the doc.
Since JSF 2.3 all the bean scopes defined in package javax.faces.bean
package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean
annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.
From JSF 2.3 here are scopes that can be used on JSF Backing Beans:
1. @javax.enterprise.context.ApplicationScoped
: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.
2. @javax.enterprise.context.SessionScoped
: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.
3. @javax.enterprise.context.ConversationScoped
: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin()
and Conversation.end()
. These methods should called explicitly, either to start or end the life of a bean.
4. @javax.enterprise.context.RequestScoped
: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
5. @javax.faces.flow.FlowScoped
: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.
6. @javax.faces.view.ViewScoped
: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.
The following legacy answer applies JSF version before 2.3
As of JSF 2.x there are 4 Bean Scopes:
- @SessionScoped
- @RequestScoped
- @ApplicationScoped
- @ViewScoped
Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.
RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.
ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.
Choose the scope you based on your requirement.
Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54]
I know it's been a while, but I'll this here in case it helps someone out.
The right answer by far is (and the selected one) the one from CommonsWare. I was having the same problem as posted, the following
MyFragmentClass fragmentList =
(MyFragmentClass) getSupportFragmentManager().findFragmentById(R.id.fragementID);
kept on returning null. My mistake was really silly, in my xml file:
<fragment
android:tag="@+id/fragementID"
android:name="com.sf.lidgit_android.content.MyFragmentClass"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
The mistake was that I had android:tag INSTEAD OF android:id.
OdeToCode has a good article covering the basic differences
As it says in the article:
Proper indexes are crucial for good performance in large databases. Sometimes you can make up for a poorly written query with a good index, but it can be hard to make up for poor indexing with even the best queries.
Quite true, too... If you're just starting out with it, I'd focus on clustered and composite indexes, since they'll probably be what you use the most.
If the view is accessed via a stored procedure, the execute grant is insufficient to access the view. You must grant select explicitly.
simply type this
grant all on to public;
I ran into this trying to revive an accidentally deleted Docker Container (oraclelinux's MySQL) from a luckily-not-removed docker volume that had the DB data in physical files.
So, all I wanted to do was to turn the data from physical files into a .sql
importable file to recreate the container with the DB and the data.
I tried biolin's solution, but ran into some [InnoDB] Multiple files found for the same tablespace ID
errors, after restart. I realized that doing open hurt surgery on certain folders/files there is quite trickey.
The solution that worked for me was temporarily changing the datadir=
in my.cnf
to the available folder and restarting the MySQL server. It did the job perfectly!
The <ul>
element has browser inherent padding & margin by default. In your case, Use
#footer ul {
margin: 0; /* To remove default bottom margin */
padding: 0; /* To remove default left padding */
}
or a CSS browser reset ( https://cssreset.com/ ) to deal with this.
function yourFunction($var1, $var2, $optional = Null){
... code
}
You can make a regular function and then add your optional variables by giving them a default Null value.
A Null is still a value, if you don't call the function with a value for that variable, it won't be empty so no error.
I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit
tries to fit a function f
that you must know to a set of points.
This is a simple 3 degree polynomial fit using numpy.polyfit
and poly1d
, the first performs a least squares polynomial fit and the second calculates the new points:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
I had actually done this from Django a while back. Open up a legitimate GMail account & enter the credentials here. Here's my code -
from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
def sendmail(to, subject, text, attach=[], mtype='html'):
ok = True
gmail_user = settings.EMAIL_HOST_USER
gmail_pwd = settings.EMAIL_HOST_PASSWORD
msg = MIMEMultipart('alternative')
msg['From'] = gmail_user
msg['To'] = to
msg['Cc'] = '[email protected]'
msg['Subject'] = subject
msg.attach(MIMEText(text, mtype))
for a in attach:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(a))
msg.attach(part)
try:
mailServer = smtplib.SMTP("smtp.gmail.com", 687)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, [to,msg['Cc']], msg.as_string())
mailServer.close()
except:
ok = False
return ok
If we have built in functions to convert your integer values to COLOR then why to worry.
string hexValue = string.Format("{0:X}", intColor);
Color brushes = System.Drawing.ColorTranslator.FromHtml("#"+hexValue);
I like this:
if (wlocation !== undefined)
But if you prefer the second way wouldn't be as you posted. It would be:
if (typeof wlocation !== "undefined")
In the case of Xamarin in VS, you must add
Theme = "@style/MyThemesss"
to youractivity.cs.
I add this and go on.
Look this:
List<Client> result = clients
.stream()
.filter(c ->
(users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
.collect(Collectors.toList());
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
Compile with O3, The compiler performs optimization well.
q = x / y;
if (x % y) ++q;
Link to a stored-procedure-less approach that Bart Gawrych posted on Dataedo site
I was asking myself, 'Do we really have to use a stored procedure here?' and I found this helpful post. (The state=0 was added to fix issues with offline databases per feedback from users of the linked page.)
declare @sql nvarchar(max);
select @sql =
(select ' UNION ALL
SELECT ' + + quotename(name,'''') + ' as database_name,
s.name COLLATE DATABASE_DEFAULT
AS schema_name,
t.name COLLATE DATABASE_DEFAULT as table_name
FROM '+ quotename(name) + '.sys.tables t
JOIN '+ quotename(name) + '.sys.schemas s
on s.schema_id = t.schema_id'
from sys.databases
where state=0
order by [name] for xml path(''), type).value('.', 'nvarchar(max)');
set @sql = stuff(@sql, 1, 12, '') + ' order by database_name,
schema_name,
table_name';
execute (@sql);
This callable function works perfectly, returns true for valid date. Be sure to call using a date on ISO format (yyyy-mm-dd or yyyy/mm/dd):
function validateDate(isoDate) {
if (isNaN(Date.parse(isoDate))) {
return false;
} else {
if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
return false;
}
}
return true;
}
Check my answer here : https://stackoverflow.com/a/50039345/2647919
"OR, even better just the ol' "drag and drop" the folder, onto your repository opened in git browser.
Open your repository in the web portal , you will see the listing of all your files. If you have just recently created the repo, and initiated with a README, you will only see the README listing.
Open your folder which you want to upload. drag and drop on the listing in browser. See the image here."
Cutting through all the chatter, the short answer is that if you turn on optimization at compile time you won't do better than this:
int i,value=5,array[1000];
for(i=0;i<1000;i++) array[i]=value;
Added bonus: the code is actually legible :)
I came here looking for the answer to the same question. But I found a much better answer myself.
In the tables list, if you right-click on the table name there is a suite of CRUD script generation options in "Send to SQL Editor". You can select multiple tables and take the same approach too.
My version of MySQL Workbench: 5.2.37
My understanding is that the SQL standard calls for case-insensitivity. I don't believe any databases follow the standard completely, though.
MySQL has a configuration setting as part of its "strict mode" (a grab bag of several settings that make MySQL more standards-compliant) for case sensitive or insensitive table names. Regardless of this setting, column names are still case-insensitive, although I think it affects how the column-names are displayed. I believe this setting is instance-wide, across all databases within the RDBMS instance, although I'm researching today to confirm this (and hoping the answer is no).
I like how Oracle handles this far better. In straight SQL, identifiers like table and column names are case insensitive. However, if for some reason you really desire to get explicit casing, you can enclose the identifier in double-quotes (which are quite different in Oracle SQL from the single-quotes used to enclose string data). So:
SELECT fieldName
FROM tableName;
will query fieldname from tablename, but
SELECT "fieldName"
FROM "tableName";
will query fieldName from tableName.
I'm pretty sure you could even use this mechanism to insert spaces or other non-standard characters into an identifier.
In this situation if for some reason you found explicitly-cased table and column names desirable it was available to you, but it was still something I would highly caution against.
My convention when I used Oracle on a daily basis was that in code I would put all Oracle SQL keywords in uppercase and all identifiers in lowercase. In documentation I would put all table and column names in uppercase. It was very convenient and readable to be able to do this (although sometimes a pain to type so many capitals in code -- I'm sure I could've found an editor feature to help, here).
In my opinion MySQL is particularly bad for differing about this on different platforms. We need to be able to dump databases on Windows and load them into UNIX, and doing so is a disaster if the installer on Windows forgot to put the RDBMS into case-sensitive mode. (To be fair, part of the reason this is a disaster is our coders made the bad decision, long ago, to rely on the case-sensitivity of MySQL on UNIX.) The people who wrote the Windows MySQL installer made it really convenient and Windows-like, and it was great to move toward giving people a checkbox to say "Would you like to turn on strict mode and make MySQL more standards-compliant?" But it is very convenient for MySQL to differ so signficantly from the standard, and then make matters worse by turning around and differing from its own de facto standard on different platforms. I'm sure that on differing Linux distributions this may be further compounded, as packagers for different distros probably have at times incorporated their own preferred MySQL configuration settings.
Here's another SO question that gets into discussing if case-sensitivity is desirable in an RDBMS.
If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.
on (release) {
getURL("http://someurl/");
}
To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.
I think it would go too far to explain into depth with pictures how to go about in stackoverflow.
The following expression worked for me:
SELECT CONVERT(VARCHAR(1000), varbinary_value, 2);
Here are more details on the choice of style (the third parameter).
you first set number of "?" in query and then by a "for" send parameters like this :
require 'dbConnect.php';
$db=new dbConnect();
$array=[];
array_push($array,'value1');
array_push($array,'value2');
$query="SELECT * FROM sites WHERE kind IN (";
foreach ($array as $field){
$query.="?,";
}
$query=substr($query,0,strlen($query)-1);
$query.=")";
$tbl=$db->connection->prepare($query);
for($i=1;$i<=count($array);$i++)
$tbl->bindParam($i,$array[$i-1],PDO::PARAM_STR);
$tbl->execute();
$row=$tbl->fetchAll(PDO::FETCH_OBJ);
var_dump($row);
You could try to assign properties to the ENUM you're trying to create and statically contruct it by using a loaded properties file. Big hack, but it works :)
Is this what you are trying to do?
# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)
# Split into individual elements by the '.' character
# Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )
# We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )
# Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
# V1 V2 V3 V4
#1 F US CLE V13
#2 F US CA6 U13
#3 F US CA6 U13
#4 F US CA6 U13
#5 F US CA6 U13
#6 F US CA6 U13
this is simple code to check email is exist or not in database
$data = $request->all(); $user = DB::table('User')->pluck('email')->toArray(); if(in_array($user,$data['email'])) { echo 'existed email'; }
What about this?
(function($) {
$(function() {
// more code using $ as alias to jQuery
// will be fired when document is ready
});
})(jQuery);
Create a new keypair: (go with the defaults)
ssh-keygen
Copy the public key to the server: (password for the last time)
ssh-copy-id [email protected]
From now on the server should recognize your key and not ask you for the password anymore:
ssh [email protected]
The compilation problem only occurs for me (gcc 4.3, ubuntu 8.10) if the three variables are global. The problem is that C doesn't work like a script languages, so you cannot take for granted that the initialization of u and t occur after the one of s. That's why you get a compilation error. Now, you cannot initialize t and y they way you did it before, that's why you will need a char*. The code that do the work is the following:
#include <stdio.h>
#include <stdlib.h>
#define STR "ABCD"
const char s[] = STR;
char* t;
char* u;
void init(){
t = malloc(sizeof(STR)-1);
t[0] = s[0];
t[1] = s[1];
t[2] = s[2];
t[3] = s[3];
u = malloc(sizeof(STR)-1);
u[0] = s[3];
u[1] = s[2];
u[2] = s[1];
u[3] = s[0];
}
int main(void) {
init();
puts(t);
puts(u);
return EXIT_SUCCESS;
}