To make a text default in a select box use the $form->select()
method. Here is how you do it.
$options = array('m'=>'Male','f'=>'Female','n'=>'neutral');
$form->select('Model.name',$options,'f');
The above code will select Female
in the list box by default.
Keep baking...
Try this coding
<div>
<iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
width: 100%; position: absolute;"></iframe>
</div>
Yes.
It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.
The following example will show you the use of multiple classes.
The first class makes the text color
red.
The second class makes the background-color
blue.
See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.
Result: multiple CSS statements in different classes will stack up.
You can read more about CSS Specificity.
.class1 {
color:red;
}
.class2 {
background-color:blue;
}
<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>
Subversion 1.5 introduces sparse checkouts which may be something you might find useful. From the documentation:
... sparse directories (or shallow checkouts) ... allows you to easily check out a working copy—or a portion of a working copy—more shallowly than full recursion, with the freedom to bring in previously ignored files and subdirectories at a later time.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
The URLs are passed in the request: request.getRequestURL()
.
If you mean other sites that are linking to you? You want to capture the HTTP Referrer, which you can do by calling:
request.getHeader("referer");
print date('H:i');
$var = date('H:i');
Should do it, for the current time. Use a lower case h
for 12 hour clock instead of 24 hour.
More date time formats listed here.
You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:
SELECT *
FROM TABLENAME
WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'
See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:
pkill -x matches the process name exactly.
pkill -x amarok
pkill -f is similar but allows a regular expression pattern.
Note that pkill with no other parameters (e.g. -x, -f) will allow partial matches on process names. So "pkill amarok" would kill amarok, amarokBanana, bananaamarok, etc.
I wish -x was the default behavior!
If your menu height is variable (for responsiveness or because it's loaded dynamically), you can set the top margin to where the fixed div ends. For example:
CSS
.fixed-header {
width: 100%;
margin: 0 auto;
position: fixed;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
z-index: 999;
}
Javascript
$(document).ready(function() {
var contentPlacement = $('#header').position().top + $('#header').height();
$('#content').css('margin-top',contentPlacement);
});
HTML
...
<div id="header" class="fixed-header"></div>
<div id="content">...</div>
...
Here's a fiddle (https://jsfiddle.net/632k9xkv/5/) that goes a little beyond this with both a fixed nav menu and header in an attempt to hopefully make this a useful sample.
#Think about how index works with string in Python,
>>> a = "123456"
>>> a[::-1]
'654321'
This also works - evaluate, if capital is defined. If not, this means, that capital is undefined or null (or other value, that evaluates to false in js)
if (capital && capital.length < 1) {do your stuff}
You can Use ngValue
. ngValue
passes sting and object both.
Pass as Object:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj.value">
{{obj.value}}
</option>
</select>
Pass as String:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj">
{{obj.value}}
</option>
</select>
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
cProfile.run('fact(126000)')
4 function calls in 5.164 seconds
Using the stack is convenient(like recursive call), but it comes at a cost: storing detailed information can take up a lot of memory.
If the stack is high, it means that the computer stores a lot of information about function calls.
The method only takes up constant memory(like iteration).
def fact(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
cProfile.run('fact(126000)')
4 function calls in 4.708 seconds
def fact(n):
return math.factorial(n)
cProfile.run('fact(126000)')
5 function calls in 0.272 seconds
Actually, this is a duplicate of Encrypt Password in Configuration Files?.
The best solution I found so far is in this answert: https://stackoverflow.com/a/1133815/1549977
Pros: Password is saved a a char array, not as a string. It's still not good, but better than anything else.
I have a C# Winforms project called SetTags with a large number of forms that I use Visual Studio 2013 to work on. After editing one of them and trying to build I got the error:
Could not load file or assembly 'SetTags Version = 2.1.85.0, Culture=neutral,PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
The error also appeared when I tried to save the project or to close the form I had been working on.
I fixed the problem by removing a recently added radio button control and commenting out all references to it, then added the control again and uncommenting the code. This allowed me to save the form, and on closing restarting VS the problem had disappeared.
My Visual Studio environment has many occasional problems - Toolbox not showing or appearing only on VS startup, unrecognized custom controls when trying to view a form in Design mode - and it may be that I need to move on to a later VS version.
You can use the cut
command:
cut -d' ' -f3,5 < datafile.txt
prints
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495
the
-d' '
- mean, use space
as a delimiter-f3,5
- take and print 3rd and 5th columnThe cut
is much faster for large files as a pure shell solution. If your file is delimited with multiple whitespaces, you can remove them first, like:
sed 's/[\t ][\t ]*/ /g' < datafile.txt | cut -d' ' -f3,5
where the (gnu) sed will replace any tab
or space
characters with a single space
.
For a variant - here is a perl solution too:
perl -lanE 'say "$F[2] $F[4]"' < datafile.txt
With classes you get inheritance and are passed by reference, structs do not have inheritance and are passed by value.
There are great WWDC sessions on Swift, this specific question is answered in close detail in one of them. Make sure you watch those, as it will get you up to speed much more quickly then the Language guide or the iBook.
$.ajax({
type: "POST",
url: hb_base_url + "consumer",
contentType: "application/json",
dataType: "json",
data: {
data__value = JSON.stringify(
{
first_name: $("#namec").val(),
last_name: $("#surnamec").val(),
email: $("#emailc").val(),
mobile: $("#numberc").val(),
password: $("#passwordc").val()
})
},
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
(RU) ?? ??????? ???? ?????? ????? ???????? ??? - $_POST['data__value']; ???????? ??? ????????? ???????? first_name ?? ???????, ????? ????????:
(EN) On the server, you can get your data as - $_POST ['data__value']; For example, to get the first_name value on the server, write:
$test = json_decode( $_POST['data__value'] );
echo $test->first_name;
My Scenario
def example():
cl = [0, 1]
def inner():
#cl = [1, 2] # access this way will throw `reference before assignment`
cl[0] = 1
cl[1] = 2 # these won't
inner()
You can't.
ANYTHING that can be read by the browser can also be read by humans. If you want something hidden, don't send it to the user's browser.
You can add all sorts of gimmicks and tricks to disable right-click and disable ctrl+U
All a user has to do is add view-source:
to the url and they will see the source right away.
Example
view-source:https://stackoverflow.com
I think onSupportNavigateUp()
is simplest and best way to do so
check the code in this link Click here for complete code
No, unfortunately this will not be possible because ConverterParameter
is not a DependencyProperty
so you won't be able to use bindings
But perhaps you could cheat and use a MultiBinding
with IMultiValueConverter
to pass in the 2 Tag
properties.
To create an option that needs no value, set the action
[docs] of it to 'store_const'
, 'store_true'
or 'store_false'
.
Example:
parser.add_argument('-s', '--simulate', action='store_true')
I just installed MySQL Server 5.7
on Windows 10
and my.ini
file is located here c:\ProgramData\MySQL\MySQL Server 5.7\my.ini
.
The Data
folder (where your dbs are created) is here C:/ProgramData/MySQL/MySQL Server 5.7\Data
.
There are also some ST2/ST3 Plugins for such tasks. I do like these two:
The first one has two methods for removing empty/unnecessary lines. One of them called Delete Surplus Blank Lines
which is cool. It removes only those lines that are followed by another empty line
The id of the input seems is not WallSearch
. Maybe you're confusing that name
and id
. They are two different properties. name
is used to define the name by which the value is posted, while id
is the unique identification of the element inside the DOM.
Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value
property.
You can use this quick start guide http://shyyko.wordpress.com/2013/07/30/zxing-with-android-quick-start/ with simple example project to build android app without IntentIntegrator.
var arr = [1, 2, 3]_x000D_
_x000D_
// ES5 syntax_x000D_
arr = arr.filter(function(item){ return item != 3 })_x000D_
_x000D_
// ES2015 syntax_x000D_
arr = arr.filter(item => item != 3)_x000D_
_x000D_
console.log( arr )
_x000D_
I had the same issue when converting databases from Access to MySQL (using vb.net to communicate with the database).
I needed to assess if a field (field type varchar(1)) was null.
This statement worked for my scenario:
SELECT * FROM [table name] WHERE [field name] = ''
A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:
t = Guide.arel_table Guide.where(t[:title].matches('%attack'))
Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.
Ishmaeel's answer generally does work, however I found one issue, which is that using OpenMappedMachineConfiguration
seems to lose your inherited section groups from machine.config. This means that you can access your own custom sections (which is all the OP wanted), but not the normal system sections. For example, this code will not work:
ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath);
Configuration configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
MailSettingsSectionGroup thisMail = configuration.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; // returns null
Basically, if you put a watch on the configuration.SectionGroups
, you'll see that system.net is not registered as a SectionGroup, so it's pretty much inaccessible via the normal channels.
There are two ways I found to work around this. The first, which I don't like, is to re-implement the system section groups by copying them from machine.config into your own web.config e.g.
<sectionGroup name="system.net" type="System.Net.Configuration.NetSectionGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<sectionGroup name="mailSettings" type="System.Net.Configuration.MailSettingsSectionGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="smtp" type="System.Net.Configuration.SmtpSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
</sectionGroup>
I'm not sure the web application itself will run correctly after that, but you can access the sectionGroups correctly.
The second solution it is instead to open your web.config as an EXE configuration, which is probably closer to its intended function anyway:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = strConfigPath };
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
MailSettingsSectionGroup thisMail = configuration.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; // returns valid object!
I daresay none of the answers provided here, neither mine or Ishmaeel's, are quite using these functions how the .NET designers intended. But, this seems to work for me.
Look at the Map interface, and at the concrete class HashMap.
To create a Map:
Map<String, String> assoc = new HashMap<String, String>();
To add a key-value pair:
assoc.put("name", "demo");
To retrieve the value associated with a key:
assoc.get("name")
And sure, you may create an array of Maps, as it seems to be what you want:
Map<String, String>[] assoc = ...
You can use merge to combine two dataframes into one:
import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')
where on specifies field name that exists in both dataframes to join on, and how
defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y')
. if you wanted to do something like star_restaurant_id
and star_restaurant_review
, you can do:
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))
The parameters are explained in detail in this link.
Ok to answer this . I simply converted my <
and the >
to <
and >
. What was happening previously is i used to set the text <script>alert('1')</script>
but before setting the text in the input text browserconverts <
and >
as <
and the >
. So hence converting them again to <
and >
since browser will understand that as only tags and converts them , than executing the script inside <input type="text" />
SELECT contendernum,totals, RANK() OVER (ORDER BY totals ASC) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
GROUP BY ContenderNum
) AS a
Console.WriteLine(Path.GetDirectoryName(@"C:\hello\my\dear\world.hm"));
Just put a space between .area1 and .item, e.g:
.area1 .item
{
color:red;
}
this style applies to elements with class item inside an element with class area1.
Think this way:
Spring MVC is a web based framework to implement the MVC architecture.
Spring Boot is a tool oriented to the programmer. Programmer must focus on programming and tool must focus on configurations. So we don't need to wast our time configuring a bunch of xml to make a simple 'Hello world'.
The best way I have found to do this, if you want to fully customize the button is to create a button, or any View you want (in my case it was a LinearLayout
) and set an OnClickListener
to that view, and call the following in the onClick event:
com.facebook.login.widget.LoginButton btn = new LoginButton(this);
btn.performClick();
Above mentioned solutions are also fine. Another solution to this problem is
If you want to import anything from top level directory. Then,
from ...module_name import *
Also, if you want to import any module from the parent directory. Then,
from ..module_name import *
Also, if you want to import any module from the parent directory. Then,
from ...module_name.another_module import *
This way you can import any particular method if you want to.
Since Ruby 2.5, it's really easy with SecureRandom.alphanumeric
:
len = 8
SecureRandom.alphanumeric(len)
=> "larHSsgL"
It generates random strings containing A-Z, a-z and 0-9 and therefore should be applicable in most use-cases. And they are generated randomly secure, which might be a benefit, too.
This is a benchmark to compare it with the solution having the most upvotes:
require 'benchmark'
require 'securerandom'
len = 10
n = 100_000
Benchmark.bm(12) do |x|
x.report('SecureRandom') { n.times { SecureRandom.alphanumeric(len) } }
x.report('rand') do
o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten
n.times { (0...len).map { o[rand(o.length)] }.join }
end
end
user system total real
SecureRandom 0.429442 0.002746 0.432188 ( 0.432705)
rand 0.306650 0.000716 0.307366 ( 0.307745)
So the rand
solution only takes about 3/4 of the time of SecureRandom
. That might matter if you generate a lot of strings, but if you just create some random string from time to time I'd always go with the more secure implementation since it is also easier to call and more explicit.
There are 3 different things we are using here :
So lets understand how spring data jpa and spring + hibernate works-
Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.
Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.
Just thought I would add to this as I had the same problem today, turns out that it was because I was returning just the function, when I wrapped it in a <div>
tag it started working, as below
renderGallery() {
const gallerySection = galleries.map((gallery, i) => {
return (
<div>
...
</div>
);
});
return (
{gallerySection}
);
}
The above caused the error. I fixed the problem by changing the return()
section to:
return (
<div>
{gallerySection}
</div>
);
...or simply:
return gallerySection
Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
above is excerpted from the Spring doc website https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html.
So, it seemed to be invoked when Spring container has started, if you want to do something at that time.
It just has one method to set the context, so you will get the context and do something to sth now already in context I think.
I've been testing v4 for a few days now and .. I'm loving it so far! It just makes sense after a while.
I also had the same question and I found handling it like the following worked best (and might even be how it is intended). It uses state, a ternary operator and <Redirect>
.
In the constructor()
this.state = {
redirectTo: null
}
this.clickhandler = this.clickhandler.bind(this);
In the render()
render(){
return (
<div>
{ this.state.redirectTo ?
<Redirect to={{ pathname: this.state.redirectTo }} /> :
(
<div>
..
<button onClick={ this.clickhandler } />
..
</div>
)
}
In the clickhandler()
this.setState({ redirectTo: '/path/some/where' });
Hope it helps. Let me know.
You could use LoadWithPartialName
. However, that is deprecated as they said.
You can indeed go along with Add-Type
, and in addition to the other answers, if you don't want to specify the full path of the .dll file, you could just simply do:
Add-Type -AssemblyName "Microsoft.SqlServer.Management.SMO"
To me this returned an error, because I do not have SQL Server installed (I guess), however, with this same idea I was able to load the Windows Forms assembly:
Add-Type -AssemblyName "System.Windows.Forms"
You can find out the precise assembly name belonging to the particular class on the MSDN site:
Working fiddle:
$.ajax({
url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
console.log(data);
}
});
I had to manually set the callback to callback
, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.
example of textarea for disable the resize option
<textarea CLASS="foo"></textarea>
<style>
textarea.foo
{
resize:none;
}
</style>
A convoluted way is to create your own Runner by subclassing org.junit.runners.BlockJUnit4ClassRunner.
You can then do something like this:
public class NameAwareRunner extends BlockJUnit4ClassRunner {
public NameAwareRunner(Class<?> aClass) throws InitializationError {
super(aClass);
}
@Override
protected Statement methodBlock(FrameworkMethod frameworkMethod) {
System.err.println(frameworkMethod.getName());
return super.methodBlock(frameworkMethod);
}
}
Then for each test class, you'll need to add a @RunWith(NameAwareRunner.class) annotation. Alternatively, you could put that annotation on a Test superclass if you don't want to remember it every time. This, of course, limits your selection of runners but that may be acceptable.
Also, it may take a little bit of kung fu to get the current test name out of the Runner and into your framework, but this at least gets you the name.
For something simple, you can combine ls with sort. For just a list of file names:
ls -1 | sort
To sort them in reverse order:
ls -1 | sort -r
I had the same issue when I changed the home directory of one use. In my case it was because of selinux
. I used the below to fix the issue:
selinuxenabled 0
setenforce 0
Yet another variation. Handles Nullables, as well as situations where the string is null and T is not nullable.
public class TypedProperty<T> : Property where T : IConvertible
{
public T TypedValue
{
get
{
if (base.Value == null) return default(T);
var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
return (T)Convert.ChangeType(base.Value, type);
}
set { base.Value = value.ToString(); }
}
}
You could use new GregorianCalendar(theYear, theMonth, theDay)
.getTime()
:
public GregorianCalendar(int year, int month, int dayOfMonth)
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
add these code into the top of your script to solve problem
@set_magic_quotes_runtime(false);
ini_set('magic_quotes_runtime', 0);
This answer is quite late to the party, but I found that the best solution was to write a shell script that used the both the screen -dmS
and nohup
commands.
screen -dmS newScreenName nohup node myserver.js >> logfile.log
I also add the >> logfile
bit on the end so I can easily save the node console.log()
statements.
Why did I use a shell script? Well I also added in an if statement that checked to see if the node myserver.js
process was already running.
That way I was able to create a single command line option that both lets me keep the server going and also restart it when I have made changes, which is very helpful for development.
Just a comment, as someone may find it useful - you can concatenate more than one string in one go:
>>> a='rabbit'
>>> b='fox'
>>> print '%s and %s' %(a,b)
rabbit and fox
ls
is part of coreutils. You can get it with git :
git clone git://git.sv.gnu.org/coreutils
You'll find coreutils listed with other packages (scroll to bottom) on this page.
Use the "match all docs" query in a delete by query command: :
You must also commit after running the delete so, to empty the index, run the following two commands:
curl http://localhost:8983/solr/update --data '<delete><query>*:*</query></delete>' -H 'Content-type:text/xml; charset=utf-8'
curl http://localhost:8983/solr/update --data '<commit/>' -H 'Content-type:text/xml; charset=utf-8'
I found the following simple solution for specifying a user in the HttpContext: https://forums.asp.net/post/5828182.aspx
With your ANDs you shouldn't have a FALSE value -2, until right at the end, e.g. with just 2 ANDs
=IF(AND(E2="In Play",F2="Closed"),3,IF(AND(E2="In Play",F2=" Suspended"),3,-2))
although it might be better with a combination of nested IFs and ANDs - try like this for the full formula:[Edited - thanks David]
=IF(E2="In Play",IF(F2="Closed",3,IF(F2="Suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-play",F2="Null"),-1,IF(AND(E2="Completed",F2="Closed"),2,IF(AND(E2="Pre-play",F2="Null"),3,-2))))
To avoid a long formula like the above you could create a table with all E2 possibilities in a column like K2:K5 and all F2 possibilities in a row like L1:N1 then fill in the required results in L2:N5 and use this formula
=INDEX($L$2:$N$5,MATCH(E2,$K$2:$K$5,0),MATCH(F2,$L$1:$N$1,0))
Sometimes it happened to me that the method described in the accepted answer didn't work, especially if the separator is a carriage return.
In those cases I solved in this way:
string='first line
second line
third line'
oldIFS="$IFS"
IFS='
'
IFS=${IFS:0:1} # this is useful to format your code with tabs
lines=( $string )
IFS="$oldIFS"
for line in "${lines[@]}"
do
echo "--> $line"
done
String body = mockMvc.perform(bla... bla).andReturn().getResolvedException().getMessage()
This should give you the body of the response. "Username already taken" in your case.
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
One of my favorite lib: Apache Commons.
The EnumUtils can do that easily.
Following an example to validate an Enum with that library:
public enum MyEnum {
DIV("div"), DEPT("dept"), CLASS("class");
private final String val;
MyEnum(String val) {
this.val = val;
}
public String getVal() {
return val;
}
}
MyEnum strTypeEnum = null;
// test if String str is compatible with the enum
// e.g. if you pass str = "div", it will return false. If you pass "DIV", it will return true.
if( EnumUtils.isValidEnum(MyEnum.class, str) ){
strTypeEnum = MyEnum.valueOf(str);
}
this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case:
you specify
transaction_status varchar(10)
but you actually trying to store
_transaction_status
which contain 19 characters.
that's why you faced this type of error in this code..
This works for me:
TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String uuid = tManager.getDeviceId();
EDIT :
You also need android.permission.READ_PHONE_STATE
set in your Manifest. Since Android M, you need to ask this permission at runtime.
See this anwser : https://stackoverflow.com/a/38782876/1339179
if you want to run the command in async mode - and print the results. you can you this class:
public static class ExecuteCmd
{
/// <summary>
/// Executes a shell command synchronously.
/// </summary>
/// <param name="command">string command</param>
/// <returns>string, as output of the command.</returns>
public static void ExecuteCommandSync(object command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
//This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
Console.WriteLine("ExecuteCommandSync failed" + objException.Message);
}
}
/// <summary>
/// Execute the command Asynchronously.
/// </summary>
/// <param name="command">string command.</param>
public static void ExecuteCommandAsync(string command)
{
try
{
//Asynchronously start the Thread to process the Execute command request.
Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
//Make the thread as background thread.
objThread.IsBackground = true;
//Set the Priority of the thread.
objThread.Priority = ThreadPriority.AboveNormal;
//Start the thread.
objThread.Start(command);
}
catch (ThreadStartException )
{
// Log the exception
}
catch (ThreadAbortException )
{
// Log the exception
}
catch (Exception )
{
// Log the exception
}
}
}
Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,
Other notes,
Keep it simple.
footer {
bottom: 0;
position: absolute;
}
You may need to also offset the height of the footer by adding a margin-bottom
equivalent to the footer height to the body
.
I think you have downloaded the .NET Reflector & this FileGenerator plugin http://filegenreflector.codeplex.com/ , If you do,
Open up the Reflector.exe,
Go to View and click Add-Ins,
In the Add-Ins window click Add...,
Then find the dll you have downloaded
FileGenerator.dll (witch came wth the FileGenerator plugin),
Then close the Add-Ins window.
Go to File and click Open and choose the dll that you want to decompile,
After you have opend it, it will appear in the tree view,
Go to Tools and click Generate Files(Crtl+Shift+G),
select the output directory and select appropriate settings as your wish, Click generate files.
OR
Have a look at py-multicast. Network module can check if an interface supports multicast (on Linux at least).
import multicast
from multicast import network
receiver = multicast.MulticastUDPReceiver ("eth0", "238.0.0.1", 1234 )
data = receiver.read()
receiver.close()
config = network.ifconfig()
print config['eth0'].addresses
# ['10.0.0.1']
print config['eth0'].multicast
#True - eth0 supports multicast
print config['eth0'].up
#True - eth0 is up
Perhaps problems with not seeing IGMP, were caused by an interface not supporting multicast?
Using j-text-utils you may print to console a table like:
And it as simple as:
TextTable tt = new TextTable(columnNames, data);
tt.printTable();
The API also allows sorting and row numbering ...
if not exist "%USERPROFILE%\.qgis-custom\" (
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
)
You have it almost done. The logic is correct, just some little changes.
This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).
If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.
If everyting is ok, files are copied.
All paths are quoted to avoid problems with spaces.
It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
In both code samples, files are not copied if the folder is not being created during the script execution.
EDITED - As dbenham comments, the same code can be written as a single line
md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
The code after the &&
will only be executed if the previous command does not set errorlevel. If mkdir
fails, xcopy
is not executed.
You can use an anchor to attempt to open the user's default mail client, prepopulated, with mailto:
, but you cannot send the actual email. *Apparently it is possible to do this with a form action as well, but browser support is varied and unreliable, so I do not suggest it.
HTML cannot send mail, you need to use a server side language like php, which is another topic. There are plently of good resources on how to do this here on SO or elsewhere on the internet.
If you are using php, I see SwiftMailer suggested quite a bit.
A class is basically a definition, and contains the object's code. An object is an instance of a class
for example if you say
String word = new String();
the class is the String class, which describes the object (instance) word.
When a class is declared, no memory is allocated so class is just a template.
When the object of the class is declared, memory is allocated.
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
bootstrap has added three css classes for text align.
I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me. I hope this helps someone.
You can transform logical implication A => B
to NOT A or B
. This is one of the most basic laws of logic. In your case it is something like this:
SELECT *
FROM logs
WHERE pw='correct' AND (id>=800 OR success=1)
AND YEAR(timestamp)=2011
I also transformed NOT id<800
to id>=800
, which is also pretty basic.
Instead of Googling for %02d
you should have been searching for sprintf()
function.
%02d
means "format the integer with 2 digits, left padding it with zeroes", so:
Format Data Result %02d 1 01 %02d 11 11
A small variation but nothing new infact. It's really missing a feature...
select info->>'name' from rabbits
where '"carrots"' = ANY (ARRAY(
select * from json_array_elements(info->'food'))::text[]);
You need to look for some replaceAll option
str = str.replace(/ /g, "+");
this is a regular expression way of doing a replaceAll.
function ReplaceAll(Source, stringToFind, stringToReplace) {
var temp = Source;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
Sorry if this answer comes so late, but maybe it can be useful for someone else. Actually there is a very useful solution to this problem, explained at the end of ?split.
> testVector <- c(1:10) #I want to divide it into 5 parts
> VectorList <- split(testVector, 1:5)
> VectorList
$`1`
[1] 1 6
$`2`
[1] 2 7
$`3`
[1] 3 8
$`4`
[1] 4 9
$`5`
[1] 5 10
I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.
let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!
If you're using SQL Server it would be something like this:
DATEDIFF(d,GETDATE(),FUTUREDATE) BETWEEN 0 AND 90
str.split()
without any arguments splits on runs of whitespace characters:
>>> s = 'I am having a very nice day.'
>>>
>>> len(s.split())
7
From the linked documentation:
If sep is not specified or is
None
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
When it is the case that you want to use any kind of external file, there is certainly a way to put them in a folder within your project, but not as valid as getting them from resources. In a regular Visual Studio project, you should have a Resources.resx
file under the Properties
section, if not, you can easily add your own Resource.resx
file. And add any kind of file in it, you can reach the walkthrough for adding resource files to your project here.
After having resource files in your project, calling them is easy as this:
var myIcon = Resources.MyIconFile;
Of course you should add the using Properties
statement like this:
using <namespace>.Properties;
Apple provides detailed, illustrated instructions covering every step of the process. Log in to the iPhone developer site and click the "program portal" link. In the program portal you'll find a link to the program portal user's guide, which is a really good reference and guide on this topic.
NP-Complete means something very specific and you have to be careful or you will get the definition wrong. First, an NP problem is a yes/no problem such that
A problem X is NP-Complete if
If X is NP-complete and a deterministic, polynomial-time algorithm exists that can solve all instances of X correctly (0% false-positives, 0% false-negatives), then any problem in NP can be solved in deterministic-polynomial-time (by reduction to X).
So far, nobody has come up with such a deterministic polynomial-time algorithm, but nobody has proven one doesn't exist (there's a million bucks for anyone who can do either: the is the P = NP problem). That doesn't mean that you can't solve a particular instance of an NP-Complete (or NP-Hard) problem. It just means you can't have something that will work reliably on all instances of a problem the same way you could reliably sort a list of integers. You might very well be able to come up with an algorithm that will work very well on all practical instances of a NP-Hard problem.
Alternatively, if your objective is to output directly to a file or stdout, you can use cat
:
cat(s1, s2, sep=", ")
You can stop the 2-line separation in the output by using
with open('t.ini') as f:
for line in f:
print line.strip()
if 'str' in line:
break
From the shell if you want to show all results you could do db.collection.find().toArray()
to get all results without it.
This worked for me, saving to child dir(temp_pdf
) under the root:
$sFilePath = $_SERVER['DOCUMENT_ROOT'] . '//temp_pdf/file.pdf' ;
$pdf->Output( $sFilePath , 'F');
Remember to make the dir writeable.
I've done this before with conditional formatting. It's a great way to visually inspect the cells in a workbook and spot the outliers in your data.
Show everything including dir itself but not its long boring contents:
find . -print -name dir -prune
Try this. Note there's no database specified - it just runs "on the server"
psql -U postgres -c "drop database databasename"
If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:
SELECT * FROM pg_prepared_xacts;
then for every id you see, run this:
ROLLBACK PREPARED '<id>';
I have to struggle to find how to achieve especial those who are new to this tool (like me)
C# code:
IWebElement ddl = ffDriver.FindElement(By.Id("ddlGoTo"));
OpenQA.Selenium.Support.UI.SelectElement clickthis = new OpenQA.Selenium.Support.UI.SelectElement(ddl);
clickthis.SelectByText("Your Text");
hope this help others!
Sometimes, default values for parameters is enough for multiple constructors. And when that doesn't suffice, I try to wrap most of the constructor functionality into an init(other-params) function that is called afterwards. Also consider using the factory concept to make an object that can effectively create the other objects you want.
http://en.wikipedia.org/w/index.php?title=Factory_method_pattern&oldid=363482142#Javascript
For Android Studio 1.5:
Update for Android Studio 2.2:
Right click on res -> new -> Image Asset
On Icon Type choose Action Bar and Tab Icons
On Asset type choose Image
On Path choose your image path
Next->Finish
The image will be saved in the /res/drawable folder.
Warning! If you choose to use images other than icons in SVG or PNG be aware that it could turn grey if the image is not transparent. You can find an answer in comments for this problem but none of these are verified by me because I never encountered this problem. I suggest you to use icons from here: Material icons
git-pull - Fetch from and integrate with another repository or a local branch GIT PULL
Basically you are pulling remote branch to your local, example:
git pull origin master
Will pull master branch into your local repository
git-rebase - Forward-port local commits to the updated upstream head GIT REBASE
This one is putting your local changes on top of changes done remotely by other users. For example:
SOME-FEATURE
Now you want to see his and your changes on your local branch.
So then you checkout master
branch:
git checkout master
then you can pull:
git pull origin master
and then you go to your branch:
git checkout SOME-FEATURE
and you can do rebase master
to get lastest changes from it and put your branch commits on top:
git rebase master
I hope now it's a bit more clear for you.
How and where is
app.run()
used? After module definition or afterapp.config()
, afterapp.controller()
?
In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js
Make it look like this
var app = angular.module('mean.dashboard', ['ui.bootstrap']);
app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
function($scope, Global, Dashboard) {
$scope.global = Global;
$scope.package = {
name: 'dashboard'
};
// ...
}
]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
Just a minor word of warning... a lot of environments use, or need, "\r\n" and not just "\n". I ran into an issue with Visual Studio not matching my regex string at the end of the line because I left off the "\r" of "\r\n", so my string couldn't match with a missing invisible character.
So, if you are doing a find, or a replace, consider the "\r".
For a little more detail on "\r" and "\n", see: https://stackoverflow.com/a/3451192/4427457
This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":
event.target.className
You can use jQuery to check for classes by name:
$(event.target).hasClass('konbo');
and to add or remove them with addClass and removeClass.
Another way, you can use a pass-through object to capture the last value and then do something with it:
List<Integer> list = new ArrayList<Integer>();
Integer lastValue = null;
for (Integer i : list) {
// do stuff
lastValue = i;
}
// do stuff with last value
To build on ccleve's answer, if you are using superagent / express / multer, on the front end side build your multipart request doing something like this:
superagent
.post(url)
.accept('application/json')
.field('myVeryRelevantJsonData', JSON.stringify({ peep: 'Peep Peep!!!' }))
.attach('myFile', file);
cf https://visionmedia.github.io/superagent/#multipart-requests.
On the express side, whatever was passed as field
will end up in req.body after doing:
app.use(express.json({ limit: '3MB' }));
Your route would include something like this:
const multerMemStorage = multer.memoryStorage();
const multerUploadToMem = multer({
storage: multerMemStorage,
// Also specify fileFilter, limits...
});
router.post('/myUploads',
multerUploadToMem.single('myFile'),
async (req, res, next) => {
// Find back myVeryRelevantJsonData :
logger.verbose(`Uploaded req.body=${JSON.stringify(req.body)}`);
// If your file is text:
const newFileText = req.file.buffer.toString();
logger.verbose(`Uploaded text=${newFileText}`);
return next();
},
...
One thing to keep in mind though is this note from the multer doc, concerning disk storage:
Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.
I guess this means it would be unreliable to, say, compute the target dir/filename based on json metadata passed along the file
With recent builds of mongodb community edition, this is straightforward.
When you install via brew, it tells you what exactly to do. There is no need to create a new launch control file.
$ brew install mongodb
==> Downloading https://homebrew.bintray.com/bottles/mongodb-3.0.6.yosemite.bottle.tar.gz ### 100.0%
==> Pouring mongodb-3.0.6.yosemite.bottle.tar.gz
==> Caveats
To have launchd start mongodb at login:
ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Then to load mongodb now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don't want/need launchctl, you can just run:
mongod --config /usr/local/etc/mongod.conf
==> Summary
/usr/local/Cellar/mongodb/3.0.6: 17 files, 159M
NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
For example, you could read your cube directly from a file into an array:
x = numpy.fromfile(file=open("data"), dtype=float).reshape((100, 100, 100))
Sum along the second dimension:
s = x.sum(axis=1)
Find which cells are above a threshold:
(x > 0.5).nonzero()
Remove every even-indexed slice along the third dimension:
x[:, :, ::2]
Also, many useful libraries work with NumPy arrays. For example, statistical analysis and visualization libraries.
Even if you don't have performance problems, learning NumPy is worth the effort.
Here is perhaps a different way for you to achieve this. Pass into the directive both the index and the item and let the directive setup the html in a template:
Demo: http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview
html:
<ul id="thumbnails">
<li class="thumbnail" ng-repeat="item in items" options='#my-container' itemdata='item' index="$index">
</li>
</ul>
js directive:
app.directive('thumbnail', [function() {
return {
restrict: 'CA',
replace: false,
transclude: false,
scope: {
index: '=index',
item: '=itemdata'
},
template: '<a href="#"><img src="{{item.src}}" alt="{{item.alt}}" /></a>',
link: function(scope, elem, attrs) {
if (parseInt(scope.index) == 0) {
angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
}
elem.bind('click', function() {
var src = elem.find('img').attr('src');
// call your SmoothZoom here
angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
});
}
}
}]);
You probably would be better off adding a ng-click to the image as pointed out in another answer.
Update
The link for the demo was incorrect. It has been updated to: http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview
I created a more comprehensive and secure password script. This will create a combination of two uppercase, two lowercase, two numbers and two special characters. Total 8 characters.
$char = [range('A','Z'),range('a','z'),range(0,9),['*','%','$','#','@','!','+','?','.']];
$pw = '';
for($a = 0; $a < count($char); $a++)
{
$randomkeys = array_rand($char[$a], 2);
$pw .= $char[$a][$randomkeys[0]].$char[$a][$randomkeys[1]];
}
$userPassword = str_shuffle($pw);
I wrote all about tabs in vim, which gives a few interesting things you didn't ask about. To automatically indent braces, use:
:set cindent
To indent two spaces (instead of one tab of eight spaces, the vim default):
:set shiftwidth=2
To keep vim from converting eight spaces into tabs:
:set expandtab
If you ever want to change the indentation of a block of text, use < and >. I usually use this in conjunction with block-select mode (v, select a block of text, < or >).
(I'd try to talk you out of using two-space indentation, since I (and most other people) find it hard to read, but that's another discussion.)
You can capture an event tab using this JQuery API.
$( "#yourInputTextId" ).keydown(function(evt) {
if(evt.key === "Tab")
//call your function
});
As of Excel 2019 you could do this. The "Error" at the end is the default.
SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")
,?\s*'.+?'|,?\s*".+?"|[^"']+?(?=,)|[^"']+
This regex works with single and double quotes and also for one quote inside another!
As some people indicated, the officially accepted answer does not quite return the external removable SD card. And i ran upon the following thread that proposes a method I've tested on some Android devices and seems to work reliably, so i thought of re-sharing here as i don't see it in the other responses:
http://forums.androidcentral.com/samsung-galaxy-s7/668364-whats-external-sdcard-path.html
Kudos to paresh996 for coming up with the answer itself, and i can attest I've tried on Samsung S7 and S7edge and seems to work.
Now, i needed a method that returned a valid path where to read files, and that considered the fact that there might not be an external SD, in which case the internal storage should be returned, so i modified the code from paresh996 to this :
File getStoragePath() {
String removableStoragePath;
File fileList[] = new File("/storage/").listFiles();
for (File file : fileList) {
if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
return file;
}
}
return Environment.getExternalStorageDirectory();
}
As postman chrome app has deprecated so, Postman Native app is available to support native plateforms. You can install Postman on Linux/Ubuntu via the Snap store using the command in terminal.
$ snap install postman
After successful installation you can find this in your applications list.
As long as you know the directory where your C++ libraries could be found at run time, this should be simple. I can clearly see that this is the case in your code. Your myDll.dll
would be present inside myLibFolder
directory inside temporary folder of the current user.
string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";
Now you can continue using the DllImport statement using a const string as shown below:
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);
Just at run time before you call the DLLFunction
function (present in C++ library) add this line of code in C# code:
string assemblyProbeDirectory = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";
Directory.SetCurrentDirectory(assemblyProbeDirectory);
This simply instructs the CLR to look for the unmanaged C++ libraries at the directory path which you obtained at run time of your program. Directory.SetCurrentDirectory
call sets the application's current working directory to the specified directory. If your myDLL.dll
is present at path represented by assemblyProbeDirectory
path then it will get loaded and the desired function will get called through p/invoke.
Also note that redirect:
and forward:
prefixes are handled by UrlBasedViewResolver
, so you need to have at least one subclass of UrlBasedViewResolver
among your view resolvers, such as InternalResourceViewResolver
.
my telepathic abilities are not particularly great, but here is what I think you want:
def merge(list_of_strings, indices):
list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
return list_of_strings
I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.
[INFO] BUILD SUCCESS
Anyway, it works for me:)
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
For those interested in the Visual Studio solution, here is the drill:
Team Explorer
window, connect to the target repo. Branches
, right-click the branch of interest and select View history
. History
window and choose Reset -> Delete changes (--hard)
.That will throw away your local commits and reset the state of your repo to the selected commit. I.e. Your changes after you pulled the repo will be lost.
You are running Composer with SSL/TLS protection disabled.
composer config --global disable-tls true
composer config --global disable-tls false
If you're using Angular 1, I would recommend using Angular's built-in method:
angular.isDefined(value);
reference : https://docs.angularjs.org/api/ng/function/angular.isDefined
Arrays are enumerable, so your foo
already is an IEnumerable<byte>
itself.
Simply use LINQ sequence methods like Take()
to get what you want out of it (don't forget to include the Linq
namespace with using System.Linq;
):
byte[] foo = new byte[4096];
var bar = foo.Take(41);
If you really need an array from any IEnumerable<byte>
value, you could use the ToArray()
method for that. That does not seem to be the case here.
There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus
void (aClass::*)(int, int)
rather than the type you try to use
void (*)(int, int)
One approach could consist in making the member function static
in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int)
.
If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void*
to your function taking function pointers and call your member through a forwarding function which obtains an object from the void*
and then calls the member function.
In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>
: you can create a suitably callable function object for these, e.g., using std::bind()
.
The type-safe approaches using a template argument for the class type or a suitable std::function<...>
are preferable than using a void*
interface as they remove the potential for errors due to a cast to the wrong type.
To clarify how to use a function pointer to call a member function, here is an example:
// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
fptr(context, 17, 42);
}
void non_member(void*, int i0, int i1) {
std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}
struct foo {
void member(int i0, int i1) {
std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
}
};
void forwarder(void* context, int i0, int i1) {
static_cast<foo*>(context)->member(i0, i1);
}
int main() {
somefunction(&non_member, nullptr);
foo object;
somefunction(&forwarder, &object);
}
If you are working on Root Directory then you can use this approach
res.sendFile(__dirname + '/FOLDER_IN_ROOT_DIRECTORY/index.html');
but if you are using Routes which is inside a folder lets say /Routes/someRoute.js
then you will need to do something like this
const path = require("path");
...
route.get("/some_route", (req, res) => {
res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
});
Try changing your code to this:
private void Test()
{
System.IO.MemoryStream data = new System.IO.MemoryStream(TestStream());
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
}
Try jQuery animate()
method, ex.
$("#divid").animate({'width':perc+'%'});
You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.*
function are thin wrappers that basically do gca().*
.
plt.subplot
returns an axes
object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
import matplotlib.pyplot as plt
ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])
ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])
and so on for as many axes as you want.
or better, wrap it all up in a loop:
import matplotlib.pyplot as plt
DATA_x = ([1, 2],
[2, 3],
[3, 4])
DATA_y = DATA_x[::-1]
XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3
for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
ax = plt.subplot(1, 3, j + 1)
ax.scatter(x, y)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
If I understand correctly, you want to know how to convert bytes encoded as a hex string to its form as an ASCII text, like "537461636B" would be converted to "Stack", in such case then the following code should solve your problem.
Have not run any benchmarks but I assume it is not the peak of efficiency.
static char ByteToAscii(const char *input) {
char singleChar, out;
memcpy(&singleChar, input, 2);
sprintf(&out, "%c", (int)strtol(&singleChar, NULL, 16));
return out;
}
int HexStringToAscii(const char *input, unsigned int length,
char **output) {
int mIndex, sIndex = 0;
char buffer[length];
for (mIndex = 0; mIndex < length; mIndex++) {
sIndex = mIndex * 2;
char b = ByteToAscii(&input[sIndex]);
memcpy(&buffer[mIndex], &b, 1);
}
*output = strdup(buffer);
return 0;
}
I had a duplicate directory (~web/web) and it removed the nested duplicate when I ran rm -rf web
while inside the first web folder.
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)
i needed to calculate the content length aswell
const formHeaders = form.getHeaders();
formHeaders["Content-Length"] = form.getLengthSync()
const config = {headers: formHeaders}
return axios.post(url, form, config)
.then(res => {
console.log(`form uploaded`)
})
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should work.
I needed a similar comparison when doing a MERGE:
WHEN MATCHED AND (Target.Field1 <> Source.Field1 OR ...)
The additional checks are to avoid updating rows where all the columns are already the same. For my purposes I wanted NULL <> anyValue
to be True, and NULL <> NULL
to be False.
The solution evolved as follows:
First attempt:
WHEN MATCHED AND
(
(
-- Neither is null, values are not equal
Target.Field1 IS NOT NULL
AND Source.Field1 IS NOT NULL
AND Target.Field1 <> Source.Field1
)
OR
(
-- Target is null but source is not
Target.Field1 IS NULL
AND Source.Field1 IS NOT NULL
)
OR
(
-- Source is null but target is not
Target.Field1 IS NOT NULL
AND Source.Field1 IS NULL
)
-- OR ... Repeat for other columns
)
Second attempt:
WHEN MATCHED AND
(
-- Neither is null, values are not equal
NOT (Target.Field1 IS NULL OR Source.Field1 IS NULL)
AND Target.Field1 <> Source.Field1
-- Source xor target is null
OR (Target.Field1 IS NULL OR Source.Field1 IS NULL)
AND NOT (Target.Field1 IS NULL AND Source.Field1 IS NULL)
-- OR ... Repeat for other columns
)
Third attempt (inspired by @THEn's answer):
WHEN MATCHED AND
(
ISNULL(
NULLIF(Target.Field1, Source.Field1),
NULLIF(Source.Field1, Target.Field1)
) IS NOT NULL
-- OR ... Repeat for other columns
)
The same ISNULL/NULLIF logic can be used to test equality and inequality:
ISNULL(NULLIF(A, B), NULLIF(B, A)) IS NULL
ISNULL(NULLIF(A, B), NULLIF(B, A)) IS NOT NULL
Here is an SQL-Fiddle demonstrating how it works http://sqlfiddle.com/#!3/471d60/1
You have to indent the docstring after the function definition there (line 3, 4):
def print_lol(the_list):
"""this doesn't works"""
print 'Ain't happening'
Indented:
def print_lol(the_list):
"""this works!"""
print 'Aaaand it's happening'
Or you can use #
to comment instead:
def print_lol(the_list):
#this works, too!
print 'Hohoho'
Also, you can see PEP 257 about docstrings.
Hope this helps!
I think the toast maybe a good method to show the value of a variable!
I am using this example in my project:
html:
<hr class="my-3 dividerClass"/>
css:
.dividerClass{
border-top-color: #999
}
Building on Luiz's answer, but satisfying the "in case of draws the item with the lowest index should be returned" condition:
from statistics import mode, StatisticsError
def most_common(l):
try:
return mode(l)
except StatisticsError as e:
# will only return the first element if no unique mode found
if 'no unique mode' in e.args[0]:
return l[0]
# this is for "StatisticsError: no mode for empty data"
# after calling mode([])
raise
Example:
>>> most_common(['a', 'b', 'b'])
'b'
>>> most_common([1, 2])
1
>>> most_common([])
StatisticsError: no mode for empty data
Try
SwingUtilities.updateComponentTreeUI(frame);
If it still doesn't work then after completing the above step try
frame.invalidate();
frame.validate();
frame.repaint();
A query (modification of https://stackoverflow.com/a/7892349/1737819) to find a custom name table size in GB. You might try this, replace 'YourTableName' with the name of your table.
SELECT
t.NAME AS TableName,
p.rows AS RowCounts,
CONVERT(DECIMAL,SUM(a.total_pages)) * 8 / 1024 / 1024 AS TotalSpaceGB,
SUM(a.used_pages) * 8 / 1024 / 1024 AS UsedSpaceGB ,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 / 1024 / 1024 AS UnusedSpaceGB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME = 'YourTable'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
UsedSpaceGB DESC, t.Name
I managed to solve this with a combination of many of the mentioned options. I’ll include a checklist of all of the things I had to do to get this to work.
In short:
NSAllowsArbitraryLoads
to true for my watch extension (not my watch app).https
and not http
.Step one:
Firstly and most obviously I had to add an NSAppTransportSecurity
key as a dictionary in my watch extension’s info.plist
with a subkey called NSAllowsArbitraryLoads
as a boolean set to true. Only set this in the watch extension and not the watch app’s plist. Although take note that this allows all connections and could be insecure.
or
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Step two:
Then I had to make sure that the url I was trying to load was https
and not just http
. For any urls that were still http I used:
Swift:
let newURLString = oldURLString.stringByReplacingOccurrencesOfString("http", withString: "https")
Obj-C:
NSString *newURLString = [oldURLString stringByReplacingOccurrencesOfString:@“http” withString:@“https”];
You will want to use the a ternary operator which acts as a shortened IF/Else statement:
echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';
In many situations, a custom attribute attached to a pd.DataFrame
object is not necessary. In addition, note that pandas
-object attributes may not serialize. So pickling will lose this data.
Instead, consider creating a dictionary with appropriately named keys and access the dataframe via dfs['some_label']
.
df = pd.DataFrame()
dfs = {'some_label': df}
The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC
See http://play.golang.org/p/vTidOlmb9P
expression
is your friend:
plot(1,1, main=expression('title'^2)) #superscript
plot(1,1, main=expression('title'[2])) #subscript
Here's the solution,
If you are a constant proxy changer like me for various reasons (university, home , workplace and so on..) you are mostly likely to get this error due to improper configuration of connection settings in the eclipse IDE. all you have to do it play around with the current settings and get it to working state. Here's how,,
1. GO TO
Window-> Preferences -> General -> Network Connection.
2. Change the Settings
Active Provider-> Manual-> and check---> HTTP, HTTPS and SOCKS
If your active provider is already set to Manual, try restoring the default (native)
That's all, restart Eclipse and you are good to go!
In Webdriver, you should use driver.switchTo().defaultContent();
to get out of a frame.
You need to get out of all the frames first, then switch into outer frame again.
// between step 4 and step 5
// remove selenium.selectFrame("relative=up");
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("cq-cf-frame");
// now continue step 6
driver.findElement(By.xpath("//button[text()='OK']")).click();
go to %appdata%\NuGet\NuGet.config
Modify this line:
<packageSources>
<add key="Microsoft Visual Studio Offline Packages" value="C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\" />
<add key="Package source" value="https://api.nuget.org/v3/index.json" />
</packageSources>
You could add google()
to repositories block
allprojects {
repositories {
jcenter()
maven {
url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'
}
maven {
url "https://jitpack.io"
}
google()
}
}
I think you can also use a postgres backup container which would backup your databases within a given time duration.
pgbackups:
container_name: Backup
image: prodrigestivill/postgres-backup-local
restart: always
volumes:
- ./backup:/backups
links:
- db:db
depends_on:
- db
environment:
- POSTGRES_HOST=db
- POSTGRES_DB=${DB_NAME}
- POSTGRES_USER=${DB_USER}
- POSTGRES_PASSWORD=${DB_PASSWORD}
- POSTGRES_EXTRA_OPTS=-Z9 --schema=public --blobs
- SCHEDULE=@every 0h30m00s
- BACKUP_KEEP_DAYS=7
- BACKUP_KEEP_WEEKS=4
- BACKUP_KEEP_MONTHS=6
- HEALTHCHECK_PORT=81
Well Curl could be a better option for json representation but in that case it would be difficult to understand the structure of json because its in command line. if you want to get your json on browser you simply remove all the XML Annotations like -
@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.NONE)
@XmlAttribute
@XmlElement
from your model class and than run the same url, you have used for xml representation.
Make sure that you have jacson-databind dependency in your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
Below command will work in command prompt:
copy c:\folder\file.ext \\dest-machine\destfolder /Z /Y
To Copy all files:
copy c:\folder\*.* \\dest-machine\destfolder /Z /Y
To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -
Hibernate Object States
Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.
Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.
Detached - A detached instance is an object that has been persistent, but its Session has been closed.
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview
Transaction Write-Behind
The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.
- To perform batch inserts and updates.
- To propagate only the last change. If an object is updated more than once, it still fires only one update statement.
http://learningviacode.blogspot.com/2012/02/write-behind-technique-in-hibernate.html
First Level Cache
Hibernate has something called 'First Level Cache'. Whenever you pass an object to save()
, update()
or saveOrUpdate()
, and whenever you retrieve an object using load()
, get()
, list()
, iterate()
or scroll()
, that object is added to the internal cache of the Session. This is where it tracks changes to various objects.
Hibernate Intercepters and Object Lifecycle Listeners -
The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html#d0e3069
This section Updated
Cascading
Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete'
from parent to child association will result in deletion of all children when a parent is deleted.
So, why are these important.
To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached
and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.
That's why hibernate (sometimes) issues a 'SELECT'
statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.
Why does hibernate issue the 'SELECT' statement only sometimes?
Hibernate issues a 'SELECT'
statement to determine what state the object is in. If the select statement returns an object, the object is in detached
state and if it does not return an object, the object is in transient
state.
Coming to your scenario -
Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached
and then re-attches it to the session and processes delete lifecycle.
Update - Since you are explicitly calling 'Update'
instead of 'SaveOrUpdate'
, hibernate blindly assumes that the object is in detached
state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.
SaveOrUpdate - If you call 'SaveOrUpdate'
, hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached
state. If the object is in transient
state, it processes the 'insert'
lifecycle and if the object is in detached
state, it processes the 'Update'
lifecycle.
They are both right-shift, but >>>
is unsigned
From the documentation:
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
You are looking for str.rsplit()
, with a limit:
print x.rsplit('-', 1)[0]
.rsplit()
searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition()
, which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition()
is the faster method as well; if you need to split more than once you can only use str.rsplit()
.
Demo:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
I know it's coming late but for those people who want to implement it purely using the JavaScript
, here's how you can do it:
tr
which is clicked.tr
DOM element.tr
parent node.HTML:
<table>
<tr>
<td>
<button id="0" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
<tr>
<td>
<button id="1" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
<tr>
<td>
<button id="2" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
In JavaScript:
function addRow() {
var evt = event.srcElement.id;
var btn_clicked = document.getElementById(evt);
var tr_referred = btn_clicked.parentNode.parentNode;
var td = document.createElement('td');
td.innerHTML = 'abc';
var tr = document.createElement('tr');
tr.appendChild(td);
tr_referred.parentNode.insertBefore(tr, tr_referred.nextSibling);
return tr;
}
This will add the new table row exactly below the row on which the button is clicked.
Imagine you have a numpy array of text like in a messenger
>>> stex[40]
array(['Know the famous thing ...
and you want to get statistics from the corpus (text col=11) you first must get the values from dataframe (df5) and then join all records together in one single corpus:
>>> stex = (df5.ix[0:,[11]]).values
>>> a_str = ','.join(str(x) for x in stex)
>>> a_str = a_str.split()
>>> fd2 = nltk.FreqDist(a_str)
>>> fd2.most_common(50)
Here is a snippet from my perl script to do this:
print OUTPUT "set arrow from $x1,$y1 to $x1,$y2 nohead lc rgb \'red\'\n";
As you might guess from above, it's actually drawn as a "headless" arrow.
I had the same problem. I solved it by removing the line break from the xml file. I did
<operationBindings>
<OperationBinding>
<operationType>update</operationType>
<operationId>makePdf</operationId>
<serverObject>
<className>com.myclass</className>
<lookupStyle>new</lookupStyle>
</serverObject>
<serverMethod>makePdf</serverMethod>
</OperationBinding>
</operationBindings>
instead of ...
<serverObject>
<className>com.myclass
</className>
<lookupStyle>new</lookupStyle>
</serverObject>
As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()
) in combination with svg's <foreignObject>
element.
You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup)
)
But note that it is mostly a hack and that there are a lot of limitations :
document.styleSheets
. for this part, DOMParser
and XMLSerializer
may help.<img>
tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).Now, a small demo of some html markup in a pseudo element :
/* _x000D_
** original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
* xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
* I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
We don't need to access the canvas context.
Implementing hednek in pure JS you would get canvas.setAttribute('style', 'background-color:#00F8')
. But my preferred method requires converting the kabab-case to camelCase.
canvas.style.backgroundColor = '#00F8'
I coudn't get any gain from transactions until I raised cache_size to a higher value i.e. PRAGMA cache_size=10000;
In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.
personally i'd suggest (for readability):
$('<div>');
some numbers on the suggestions so far (safari 3.2.1 / mac os x):
var it = 50000;
var start = new Date().getTime();
for (i = 0; i < it; ++i) {
// test creation of an element
// see below statements
}
var end = new Date().getTime();
alert( end - start );
var e = $( document.createElement('div') ); // ~300ms
var e = $('<div>'); // ~3100ms
var e = $('<div></div>'); // ~3200ms
var e = $('<div/>'); // ~3500ms
DataTable
's Select
method only supports simple filtering expressions like {field} = {value}
. It does not support complex expressions, let alone SQL/Linq statements.
You can, however, use Linq extension methods to extract a collection of DataRow
s then create a new DataTable
.
dt = dt.AsEnumerable()
.GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
.Select(g => g.OrderBy(r => r["PK"]).First())
.CopyToDataTable();
The basic one, ask tasklist to filter its output and only show the indicated process id information
tasklist /fi "pid eq 4444"
To only get the process name, the line must be splitted
for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a
In this case, the list of processes is retrieved without headers (/nh
) in csv format (/fo:csv
). The commas are used as token delimiters and the first token in the line is the image name
note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command
for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a
This will generate the task list and filter it searching for the process id in the second column of the csv output.
edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.
tasklist /fi "idp eq 4444"
$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");
$sql->execute();
$fetch = $sql->fetch(PDO::FETCH_ASSOC);
// if not empty result
if (is_array($fetch)) {
$_SESSION["userMember"] = $fetch["username"];
$_SESSION["password"] = $fetch["password"];
echo 'yes this member is registered';
}else {
echo 'empty result!';
}
Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64
macro and other printf
issues altogether:
#include <fmt/core.h>
int main() {
uint64_t ui64 = 90;
fmt::print("test uint64_t : {}\n", ui64);
}
The formatting facility based on this library is proposed for standardization in C++20: P0645.
Disclaimer: I'm the author of {fmt}.
This workflow works best for me:
git checkout -b develop
...make some changes...
...notice master has been updated...
...commit changes to develop...
git checkout master
git pull
...bring those changes back into develop...
git checkout develop
git rebase master
...make some more changes...
...commit them to develop...
...merge them into master...
git checkout master
git pull
git merge develop
this worked for me:-
<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>
thanks for sharing code...
Array
(
[__ci_last_regenerate] => 1490879962
[user_id] => 3
[designation_name] => Admin
[region_name] => admin
[territory_name] => admin
[designation_id] => 2
[region_id] => 1
[territory_id] => 1
[employee_user_id] => mosin11
)
This way works and with this structure you can create your own framework and do it with less boilerplate.
Sorry if some error is present, I'm writing this handly with my cellphone
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>
Person.java (Person Object Class)
Class Person {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
PersonController.java (Person Controller)
@RestController
public class PersonController implements Controller {
@RequestMapping("/person")
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
Person person = new Person();
person.setName("Person's name");
Gson gson = new Gson();
ModelAndView modelAndView = new ModelAndView("person");
modelAndView.addObject("person", gson.toJson(person));
return modelAndView;
}
}
person.jsp
<html>
<head>
<title>Person Example</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="personScript.js"></script>
</head>
<body>
<h1>Person/h1>
<input type="hidden" id="person" value="${person}">
</body>
</html>
personScript.js
function parseJSON(data) {
return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))();
}
$(document).ready(function() {
var personJson = $('#person');
person = parseJSON(personJson.val());
alert(person.name);
});
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}
Here's an example that uses the class:
try {
// Generate a temporary key. In practice, you would save this key.
// See also Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt("Don't tell anybody!");
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}
There is no way to identify the charset of a string that is completely accurate. There are ways to try to guess the charset. One of these ways, and probably/currently the best in PHP, is mb_detect_encoding(). This will scan your string and look for occurrences of stuff unique to certain charsets. Depending on your string, there may not be such distinguishable occurrences.
Take the ISO-8859-1 charset vs ISO-8859-15 ( http://en.wikipedia.org/wiki/ISO/IEC_8859-15#Changes_from_ISO-8859-1 )
There's only a handful of different characters, and to make it worse, they're represented by the same bytes. There is no way to detect, being given a string without knowing it's encoding, whether byte 0xA4 is supposed to signify ¤ or € in your string, so there is no way to know it's exact charset.
(Note: you could add a human factor, or an even more advanced scanning technique (e.g. what Oroboros102 suggests), to try to figure out based upon the surrounding context, if the character should be ¤ or €, though this seems like a bridge too far)
There are more distinguishable differences between e.g. UTF-8 and ISO-8859-1, so it's still worth trying to figure it out when you're unsure, though you can and should never rely on it being correct.
Interesting read: http://kore-nordmann.de/blog/php_charset_encoding_FAQ.html#how-do-i-determine-the-charset-encoding-of-a-string
There are other ways of ensuring the correct charset though. Concerning forms, try to enforce UTF-8 as much as possible (check out snowman to make sure yout submission will be UTF-8 in every browser: http://intertwingly.net/blog/2010/07/29/Rails-and-Snowmen ) That being done, at least you're can be sure that every text submitted through your forms is utf_8. Concerning uploaded files, try running the unix 'file -i' command on it through e.g. exec() (if possible on your server) to aid the detection (using the document's BOM.) Concerning scraping data, you could read the HTTP headers, that usually specify the charset. When parsing XML files, see if the XML meta-data contain a charset definition.
Rather than trying to automagically guess the charset, you should first try to ensure a certain charset yourself where possible, or trying to grab a definition from the source you're getting it from (if applicable) before resorting to detection.
I've written a post about this once: Resolving circular dependencies in c++
The basic technique is to decouple the classes using interfaces. So in your case:
//Printer.h
class Printer {
public:
virtual Print() = 0;
}
//A.h
#include "Printer.h"
class A: public Printer
{
int _val;
Printer *_b;
public:
A(int val)
:_val(val)
{
}
void SetB(Printer *b)
{
_b = b;
_b->Print();
}
void Print()
{
cout<<"Type:A val="<<_val<<endl;
}
};
//B.h
#include "Printer.h"
class B: public Printer
{
double _val;
Printer* _a;
public:
B(double val)
:_val(val)
{
}
void SetA(Printer *a)
{
_a = a;
_a->Print();
}
void Print()
{
cout<<"Type:B val="<<_val<<endl;
}
};
//main.cpp
#include <iostream>
#include "A.h"
#include "B.h"
int main(int argc, char* argv[])
{
A a(10);
B b(3.14);
a.Print();
a.SetB(&b);
b.Print();
b.SetA(&a);
return 0;
}
You set path of route is ''. Example for DashboardComponent is load first.
@Routes([
{ path: '', component: DashboardComponent },
{ path: '/ConfigManager', component: ConfigManagerComponent },
{ path: '/Merge', component: MergeComponent },
{ path: '/ApplicationManagement', component: ApplicationMgmtComponent }
])
Hope it help you.
you can change that using label property in property panel. This screen shot is example that
In Java you can do:
int myInt=4;
Long myLong= new Long(myInt);
in your case it would be:
content.setSequence(new Long(i));
In my case I had to specify the Port Number using
scp -P 2222 username@hostip:/directory/ /localdirectory/
I used this, very cool tool
https://wordpress.org/plugins/php-settings/
This plugin provides a simple user interface with a code editor to edit your local .ini settings.
This can be used to change settings like
upload_max_filesize
or max_execution_time
which are often set to very low values by the hosting companies.
Do you mean altering the table after it has been created? If so you need to use alter table, in particular:
ALTER TABLE tablename MODIFY COLUMN new-column-definition
e.g.
ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);
I'm not sure if this is what you want but:
Directory.GetFiles(@"c:\mydir", "*.flv");
Or:
Path.GetExtension(@"c:\test.flv")
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:
var mahByteArray = new ArrayList<byte>();
If you have a byte array from elsewhere, you can use the AddRange function.
mahByteArray.AddRange(mahOldByteArray);
Then you can use Add() and Insert() to add elements.
mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.
Need it back in an array? .ToArray() has you covered!
mahOldByteArray = mahByteArray.ToArray();
for showing as a string, simply use:
console.log("they are: " + JSON.stringify(foo));
Actually NULL filter is not being ignored. Thing is this is how joining two tables work.
I will try to walk down with the steps performed by database server to make it understand.
For example when you execute the query which you said is ignoring the NULL condition.
SELECT
*
FROM
shipments s
LEFT OUTER JOIN returns r
ON s.id = r.id
AND r.id is null
WHERE
s.day >= CURDATE() - INTERVAL 10 DAY
1st thing happened is all the rows from table SHIPMENTS get selected
on next step database server will start selecting one by one record from 2nd(RETURNS) table.
on third step the record from RETURNS table will be qualified against the join conditions you have provided in the query which in this case is (s.id = r.id and r.id is NULL)
note that this qualification applied on third step only decides if server should accept or reject the current record of RETURNS table to append with the selected row of SHIPMENT table. It can in no way effect the selection of record from SHIPMENT table.
And once server is done with joining two tables which contains all the rows of SHIPMENT table and selected rows of RETURNS table it applies the where clause on the intermediate result. so when you put (r.id is NULL) condition in where clause than all the records from the intermediate result with r.id = null gets filtered out.
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Check this link: http://css-tricks.com/snippets/jquery/smooth-scrolling/ for a demo, I've used it before and it works quite nicely.
showModalBottomSheet(
context: context,
builder: (context) => Container(
color: Color(0xff757575), //background color
child: new Container(
decoration: new BoxDecoration(
color: Colors.blue,
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(40.0),
topRight: const Radius.circular(40.0))
),
child: new Center(
child: new Text("Hi modal sheet"),
)
),
)
This is will make your container color the same as the background color. And there will be a child container of the same height-width with blue color. This will make the corner with the same color as the background color.
I had the same issue, but I needed to display multiple lines (where text-overflow: ellipsis;
fails). I solve it using a textarea
inside a TD
and then style it to behave like a table cell.
textarea {
margin: 0;
padding: 0;
width: 100%;
border: none;
resize: none;
/* Remove blinking cursor (text caret) */
color: transparent;
display: inline-block;
text-shadow: 0 0 0 black; /* text color is set to transparent so use text shadow to draw the text */
&:focus {
outline: none;
}
}
Thanks Notable1, works for me with the tidytextr Create a dataframe with the name of files in one column and content in other.
diretorio <- "D:/base"
arquivos <- list.files(diretorio, pattern = "*.PDF")
quantidade <- length(arquivos)
#
df = NULL
for (k in 1:quantidade) {
nome = arquivos[k]
print(nome)
Sys.sleep(1)
dados = read_pdf(arquivos[k],ocr = T)
print(dados)
Sys.sleep(1)
df = rbind(df, data.frame(nome,dados))
Sys.sleep(1)
}
Encoding(df$text) <- "UTF-8"
Yes you can, but instead of blank, simply return null
if you don't want to render
anything from component, like this:
return (null);
Another important point is, inside JSX if you are rendering element conditionally, then in case of condition=false
, you can return any of these values false, null, undefined, true
. As per DOC:
booleans (true/false), null, and undefined
are valid children, they will be Ignored means they simply don’t render.
All these JSX
expressions will render to the same thing:
<div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>
Example:
Only odd values will get rendered, because for even values we are returning null
.
const App = ({ number }) => {_x000D_
if(number%2) {_x000D_
return (_x000D_
<div>_x000D_
Number: {number}_x000D_
</div>_x000D_
)_x000D_
}_x000D_
_x000D_
return (null); //===> notice here, returning null for even values_x000D_
}_x000D_
_x000D_
const data = [1,2,3,4,5,6];_x000D_
_x000D_
ReactDOM.render(_x000D_
<div>_x000D_
{data.map(el => <App key={el} number={el} />)}_x000D_
</div>,_x000D_
document.getElementById('app')_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='app' />
_x000D_
From a Java Game Engine:
/**
* Converts a given Image into a BufferedImage
*
* @param img The Image to be converted
* @return The converted BufferedImage
*/
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
Toolbar customization can done by following ways
write button and textViews code inside toolbar as shown below
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:layout_width="wrap_content"
android:layout_height="@dimen/btn_height_small"
android:text="Departure"
android:layout_gravity="right"
/>
</android.support.v7.widget.Toolbar>
Other way is to use item menu as shown below
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
If you are using a template engine like Asp.net Razor Engine or Angular, I think you must re-generate your page and split the page in several pages and then you can freely markup each page and put header and footer on theme. one example could be as bellow:
@page {_x000D_
size: A4; _x000D_
margin: .9cm;_x000D_
}_x000D_
_x000D_
_x000D_
@media print {_x000D_
_x000D_
body.print-paper-a4 {_x000D_
width: 210mm;_x000D_
height: 297mm;_x000D_
}_x000D_
_x000D_
body {_x000D_
background: white;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.print-stage,_x000D_
.no-print {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
_x000D_
body.print-paper.a4 .print-paper {_x000D_
width: 210mm;_x000D_
height: 297mm;_x000D_
}_x000D_
_x000D_
.print-paper {_x000D_
page-break-after: always;_x000D_
margin: 0;_x000D_
padding: .8cm;_x000D_
border:none;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
.print-papers {_x000D_
display: block;_x000D_
z-index: 2000;_x000D_
margin: auto;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
body.print-paper-a4 .print-paper {_x000D_
width: 21cm;_x000D_
height:27cm;_x000D_
}_x000D_
_x000D_
_x000D_
.print-paper {_x000D_
margin: auto;_x000D_
background: white;_x000D_
border: 1px dotted black;_x000D_
box-sizing: border-box;_x000D_
margin: 1cm auto;_x000D_
padding: .8cm;_x000D_
overflow: hidden; _x000D_
}_x000D_
_x000D_
_x000D_
body.print-mode .no-print-preview {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
body.print-mode .print-preview {_x000D_
display: block;_x000D_
}
_x000D_
<body class="print-mode print-paper-a4">_x000D_
_x000D_
<div class="print-papers print-preview">_x000D_
<div class="print-paper">_x000D_
<div style="font-size: 5cm">_x000D_
HELLO_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
<div class="print-paper">_x000D_
<div class="page-header">_x000D_
</div>_x000D_
_x000D_
_x000D_
</div>_x000D_
<div class="print-paper">_x000D_
_x000D_
_x000D_
_x000D_
</div> _x000D_
</div>_x000D_
</body>
_x000D_
PS C:\> $MyVar = "C:\MyTxt.txt"
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
True
($MyVar -ne $null)
returned true and (Get-Content $MyVar)
also returned true.
PS C:\> $MyVar = $null
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
False
($MyVar -ne $null)
returned false and so far I must assume the (Get-Content $MyVar)
also returned false.
PS C:\> ($MyVar -ne $null) -and (Get-Content "C:\MyTxt.txt")
False
($MyVar -ne $null)
returned false and proved the second condition (Get-Content "C:\MyTxt.txt")
never ran, by returning false on the whole command.
Use fileReader.readAsDataURL( fileObject )
, this will encode it to base64, which you can safely upload to your server.
I found the problem. This code was placed in a separate file that was added with a php include() function. And this include was happening before the Bootstrap files were loaded. So the Bootstrap JS file was not loaded yet, causing this modal to not do anything.
With the above code sample is nothing wrong and works as intended when placed in the body part of a html page.
<script type="text/javascript">
$('#memberModal').modal('show');
</script>