You're obviously not disposing of things.
Consider the "using" command when temporarily using objects that implement IDisposable.
<script>_x000D_
document.onkeydown = function(e) {_x000D_
if(event.keyCode == 123) {_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'E'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'H'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'A'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'E'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
}_x000D_
</script>
_x000D_
Try this code
Although not technically grep nor command line, both Microsoft Visual Studio and Notepad++ have a very good Find in Files feature with full regular expression support. I find myself using them frequently even though I also have the CygWin version of grep available on the command line.
I need a presence of href attribute's value for degradation (when js is switched off), so I can't use empty href attribute (or "#"), but the code above did not work for me, because i need an event (e) variable. I created my own directive:
angular.module('MyApp').directive('clickPrevent', function() {
return function(scope, element, attrs) {
return element.on('click', function(e) {
return e.preventDefault();
});
};
});
In HTML:
<a data-click-prevent="true" href="/users/sign_up" ng-click="openSignUpModal()">Sign up</a>
The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....
About the libraries you could use are.
And there could be many more, but that are what I've used
About the json I don't now maybe something like this
public class GetQuestions
{
public List<Student> Questions { get; set; }
}
public class Student
{
public string Code { get; set; }
public string Questions { get; set; }
}
void Main()
{
var gq = new GetQuestions
{
Questions = new List<Student>
{
new Student {Code = "s1", Questions = "Q1,Q2"},
new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
}
};
//Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
JsonConvert.SerializeObject(gq).Dump();
}
and the result is this
{
"Questions":[
{"Code":"s1","Questions":"Q1,Q2"},
{"Code":"s2","Questions":"Q1,Q2,Q3"},
{"Code":"s3","Questions":"Q1,Q2,Q4"},
{"Code":"s4","Questions":"Q1,Q2,Q5"}
]
}
Yes I know the json is different, but the json that you want with dictionary.
void Main()
{
var f = new Foo
{
GetQuestions = new Dictionary<string, string>
{
{"s1", "Q1,Q2"},
{"s2", "Q1,Q2,Q3"},
{"s3", "Q1,Q2,Q4"},
{"s4", "Q1,Q2,Q4,Q6"},
}
};
JsonConvert.SerializeObject(f).Dump();
}
class Foo
{
public Dictionary<string, string> GetQuestions { get; set; }
}
And with Dictionary is as you want it.....
{
"GetQuestions":
{
"s1":"Q1,Q2",
"s2":"Q1,Q2,Q3",
"s3":"Q1,Q2,Q4",
"s4":"Q1,Q2,Q4,Q6"
}
}
SUBSTR (documentation):
SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName from shipment
When selected, it's like any other column. You should give it a name (with As
keyword), and you can selected other columns in the same statement:
SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName, column2, ... from shipment
i had the same issue and find the solution lately.
you should check if your route is rather inside a route::group
like here:
Route::group(['prefix' => 'Auth', 'as' => 'Auth.', 'namespace' => 'Auth', 'middleware' => 'Auth']
if so you should use it in the view file. like here:
!! Form::model(Auth::user(), ['method' => 'PATCH', 'route' => 'Auth.preferences/' . Auth::user()->id]) !!}
One option would be:
SET SERVEROUTPUT ON
EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));
You can select the rows from the table you want to export in the MySQL Workbench SQL Editor. You will find an Export button in the resultset that will allow you to export the records to a CSV file, as shown in the following image:
Please also keep in mind that by default MySQL Workbench limits the size of the resultset to 1000 records. You can easily change that in the Preferences dialog:
Hope this helps.
in JDK 8, jdbc odbc bridge is no longer used and thus removed fro the JDK. to use Microsoft Access database in JAVA, you need 5 extra JAR libraries.
1- hsqldb.jar
2- jackcess 2.0.4.jar
3- commons-lang-2.6.jar
4- commons-logging-1.1.1.jar
5- ucanaccess-2.0.8.jar
add these libraries to your java project and start with following lines.
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<Path to your database i.e. MS Access DB>");
Statement s = conn.createStatement();
path could be like E:/Project/JAVA/DBApp
and then your query to be executed. Like
ResultSet rs = s.executeQuery("SELECT * FROM Course");
while(rs.next())
System.out.println(rs.getString("Title") + " " + rs.getString("Code") + " " + rs.getString("Credits"));
certain imports to be used. try catch block must be used and some necessary things no to be forgotten.
Remember, no need of bridging drivers like jdbc odbc or any stuff.
if you're using reactive forms then you can use the following way. consider the following example.
`<p class="mr-3"> Require Shipping:
<input type="radio" class="ml-2" value="true" name="requiresShipping"
id="requiresShipping" formControlName="requiresShipping">
Yes
<input type="radio" class="ml-2" value="false" name="requiresShipping"
id="requiresShipping" formControlName="requiresShipping">
No
</p>`
`
export class ClassName implements OnInit {
public yourForm: FormGroup
constructor(
private fromBuilder: FormBuilder
) {
this.yourForm= this.fromBuilder.group({
requiresShipping: this.fromBuilder.control('true'),
})
}
}
`
now you will get the default selected radio button.
I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.
The core function
public int Recv(byte[] buffer, int maxLen)
has name and works like "well known" socket's recv()
.
It means that
TimeoutException
.maxLen
bytes .
public class Uart : SerialPort
{
private int _receiveTimeout;
public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }
static private string ComPortName = "";
/// <summary>
/// It builds PortName using ComPortNum parameter and opens SerialPort.
/// </summary>
/// <param name="ComPortNum"></param>
public Uart(int ComPortNum) : base()
{
base.BaudRate = 115200; // default value
_receiveTimeout = 2000;
ComPortName = "COM" + ComPortNum;
try
{
base.PortName = ComPortName;
base.Open();
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("Error: Port {0} is in use", ComPortName);
}
catch (Exception ex)
{
Console.WriteLine("Uart exception: " + ex);
}
} //Uart()
/// <summary>
/// Private property returning positive only Environment.TickCount
/// </summary>
private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }
/// <summary>
/// It uses SerialPort.BaseStream rather SerialPort functionality .
/// It Receives up to maxLen number bytes of data,
/// Or throws TimeoutException if no any data arrived during ReceiveTimeout.
/// It works likes socket-recv routine (explanation in body).
/// Returns:
/// totalReceived - bytes,
/// TimeoutException,
/// -1 in non-ComPortNum Exception
/// </summary>
/// <param name="buffer"></param>
/// <param name="maxLen"></param>
/// <returns></returns>
public int Recv(byte[] buffer, int maxLen)
{
/// The routine works in "pseudo-blocking" mode. It cycles up to first
/// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
/// If no any message received during ReceiveTimeout property,
/// the routine throws TimeoutException
/// In other hand, if any data has received, first no-data cycle
/// causes to exit from routine.
int TimeOutSpan = 2;
// counts delay in TimeOutSpan-s after end of data to break receive
int EndOfDataCnt;
// pseudo-blocking timeout counter
int TimeOutCnt = _tickCount + _receiveTimeout;
//number of currently received data bytes
int justReceived = 0;
//number of total received data bytes
int totalReceived = 0;
BaseStream.ReadTimeout = TimeOutSpan;
//causes (2+1)*TimeOutSpan delay after end of data in UART stream
EndOfDataCnt = 2;
while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
{
try
{
justReceived = 0;
justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
totalReceived += justReceived;
if (totalReceived >= maxLen)
break;
}
catch (TimeoutException)
{
if (totalReceived > 0)
EndOfDataCnt--;
}
catch (Exception ex)
{
totalReceived = -1;
base.Close();
Console.WriteLine("Recv exception: " + ex);
break;
}
} //while
if (totalReceived == 0)
{
throw new TimeoutException();
}
else
{
return totalReceived;
}
} // Recv()
} // Uart
Output from subprocess.call()
should only be redirected to files.
You should use subprocess.Popen()
instead. Then you can pass subprocess.PIPE
for the stderr, stdout, and/or stdin parameters and read from the pipes by using the communicate()
method:
from subprocess import Popen, PIPE
p = Popen(['program', 'arg1'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode
The reasoning is that the file-like object used by subprocess.call()
must have a real file descriptor, and thus implement the fileno()
method. Just using any file-like object won't do the trick.
See here for more info.
Might be useful to some : check for
pointer-events: none;
In the CSS. It prevents clicks from being caught by JS. I think it's relevant because the CSS might be the last place you'd look into in this kind of situation.
Ideone supports Python 2.6 and Python 3
No. Apps can only modify files within the documents directory, within their own sandbox. This is for security, and ease of installing/uninstalling. So you could only do this on a jailbroken device.
The syntax is
pid_t waitpid(pid_t pid, int *statusPtr, int options);
1.where pid is the process of the child it should wait.
2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.
3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:
WNOHANG WUNTRACED WCONTINUED
If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.
benifits over wait
1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes
2.waitpid supports job control
3.it supports non blocking of the parent process
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.
If you are using native javascript then you can use this code -
let ids = users.map(function(obj, index) {
return obj.id;
})
console.log(ids); //[12, 14, 16, 18]
To me, handling exception can be seen as business rule. Obviously, the first approach is unacceptable. The second one is better one and it might be 100% correct way IF the context says so. Now, for example, you are developing an Outlook Addin. If you addin throws unhandled exception, the outlook user might now know it since the outlook will not destroy itself because of one plugin failed. And you have hard time to figure out what went wrong. Therefore, the second approach in this case, to me, it is a correct one. Beside logging the exception, you might decide to display error message to user - i consider it as a business rule.
You can do like
$timeout(function() {
angular.element('#btn2').triggerHandler('click');
});
Changing IE's JSON mime-type settings will effect the way IE treats all JSON responses.
Changing the mime-type header to text/html will effectively tell any browser that the JSON response you are returning is not JSON but plain text.
Neither options are preferable.
Instead you would want to use a plugin or tool like the above mentioned Fiddler or any other network traffic inspector proxy where you can choose each time how to process the JSON response.
One thing to watch out for (at least this tripped me up) was that I was removing the constraint from the wrong view. The constraint I was trying to remove was not a child constraint of my view so when I did
myView.removeConstraint(theConstraint)
it wasn't actually removing anything because I needed to call
myView.superView.removeConstraint(theConstraint)
since the constraint was technically sibling constraint of my view.
I like to do this with sed. In you case:
for x in DET01-*.dat; do
echo $x | sed -r 's/DET01-ABC-(.+)\.dat/mv -v "\0" "DET01-XYZ-\1.dat"/'
done | sh -e
It is best to omit the "sh -e" part first to see what will be executed.
git stash
+ rebase
automation
For when I need to modify an old commit a lot of times for Gerrit reviews, I've been doing:
git-amend-old() (
# Stash, apply to past commit, and rebase the current branch on to of the result.
current_branch="$(git rev-parse --abbrev-ref HEAD)"
apply_to="$1"
git stash
git checkout "$apply_to"
git stash apply
git add -u
git commit --amend --no-edit
new_sha="$(git log --format="%H" -n 1)"
git checkout "$current_branch"
git rebase --onto "$new_sha" "$apply_to"
)
Usage:
git add
if already in repogit-amend-old $old_sha
I like this over --autosquash
as it does not squash other unrelated fixups.
Using Perl:
perl -ne 'print if /\S/'
\S
means match non-blank characters.
Look at this code, it can help you to get out of the loop fast!
foreach (var name in parent.names)
{
if (name.lastname == null)
{
Violated = true;
this.message = "lastname reqd";
break;
}
else if (name.firstname == null)
{
Violated = true;
this.message = "firstname reqd";
break;
}
}
Gson is also good for it: http://code.google.com/p/google-gson/
" Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. "
Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Using Ubuntu, got the same issue I noticed that the owner of some of the directories in ~/workspace/.metadata/.plugins/ ...etc... was root changed owner to me and the error stopped happening.
Looks like the same sort of issue may be caused by multiple causes.
Starting from Windows Vista, a service cannot interact with the desktop. You will not be able to see any windows or console windows that are started from a service. See this MSDN forum thread.
On other OS, there is an option that is available in the service option called "Allow Service to interact with desktop". Technically, you should program for the future and should follow the Vista guideline even if you don't use it on Vista.
If you still want to run an application that never interact with the desktop, try specifying the process to not use the shell.
ProcessStartInfo info = new ProcessStartInfo(@"c:\myprogram.exe");
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
info.ErrorDialog = false;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(info);
See if this does the trick.
First you inform Windows that the program won't use the shell (which is inaccessible in Vista to service).
Secondly, you redirect all consoles interaction to internal stream (see process.StandardInput
and process.StandardOutput
.
Look at your import
statements at the top. If you are saying import android.R
, then there that is a problem. It might not be the only one as these 'R' errors can be tricky, but it would definitely definitely at least part of the problem.
If that doesn't fix it, make sure your eclipse plugin(ADT) and your android SDK are fully up to date, remove the project from the emulator/phone by manually deleting it from the OS, and clean the project (Launch Eclipse->Project->Clean...). Sounds silly to make sure your stuff is fully up to date, but the earlier versions of the ADT and SDK has a lot of annoying bugs related to the R files that have since been cleared up.
Just FYI, the stuff that shows up in the R class is generated from the stuff in your project res (aka resources) folder. The R class allows you to reference a resource (such as an image or a string) without having to do file operations all over the place. It does other stuff too, but that's for another answer. Android OS uses a similar scheme - it has a resources folder and the class android.R is the way to access stuff in the android resources folder. The problem arises when in a single class you are using both your own resources, and standard android resources. Normally you can say import
at the top, and then reference a class just using the last bit of the name (for example, import java.util.List
allows you to just write List
in your class and the compiler knows you mean java.util.List
). When you need to use two classes that are named the same thing, as is the case with the auto-generated R class, then you can import one of them and you have to fully qualify the other one whenever you want to mean it. Typically I import the R file for my project, and then just say android.R.whatever when I want an android resource.
Also, to reiterate Andy, don't modify the R file automatically. That's not how it's meant to be used.
If you just need read-only access, then c_str()
will do it:
char const *c = myString.c_str();
If you need read/write access, then you can copy the string into a vector. vectors manage dynamic memory for you. You don't have to mess with allocation/deallocation then:
std::vector<char> bytes(myString.begin(), myString.end());
bytes.push_back('\0');
char *c = &bytes[0];
To output an object to the console, you have to stringify the object first:
success:function(data){
console.log(JSON.stringify(data));
}
One quick way to do this is to create a column with a formula that evaluates to true for the rows you care about and then filter for the value TRUE in that column.
I suggest to use jQuery:
$('#mydiv')
.css('cursor', 'pointer')
.click(
function(){
alert('Click event is fired');
}
)
.hover(
function(){
$(this).css('background', '#ff00ff');
},
function(){
$(this).css('background', '');
}
);
You can also try: (I tried this and it worked for me)
SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;
Try \n\n , it will work! :)
public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}
Used this to convert any String number to double when u need int just convert the data type from num and num2 to int ; took all the cases for any string double with Eng:"Bader Qandeel"
public static double str2doubel(String str) {
double num = 0;
double num2 = 0;
int idForDot = str.indexOf('.');
boolean isNeg = false;
String st;
int start = 0;
int end = str.length();
if (idForDot != -1) {
st = str.substring(0, idForDot);
for (int i = str.length() - 1; i >= idForDot + 1; i--) {
num2 = (num2 + str.charAt(i) - '0') / 10;
}
} else {
st = str;
}
if (st.charAt(0) == '-') {
isNeg = true;
start++;
} else if (st.charAt(0) == '+') {
start++;
}
for (int i = start; i < st.length(); i++) {
if (st.charAt(i) == ',') {
continue;
}
num *= 10;
num += st.charAt(i) - '0';
}
num = num + num2;
if (isNeg) {
num = -1 * num;
}
return num;
}
The other answers do not seem to touch on a key aspect here, and that is you make no mention of requiring supporting a web browser as a client. Most of the limitations of plain HTTP above are assuming you would be working with browser/ JS implementations.
The HTTP protocol is fully capable of full-duplex communication; it is legal to have a client perform a POST with a chunked encoding transfer, and a server to return a response with a chunked-encoding body. This would remove the header overhead to just at init time.
So if all you're looking for is full-duplex, control both client and server, and are not interested in extra framing/features of WebSockets, then I would argue that HTTP is a simpler approach with lower latency/CPU (although the latency would really only differ in microseconds or less for either).
A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
The ModelState property on the controller is actually a ModelStateDictionary object. You can iterate through the keys on the dictionary and use the IsValidField method to check if that particular field is valid.
In chart.js 2.1.6, I did something like this (in typescript):
let that = this;
options = {
legend: {
display: false,
responsive: false
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
let account: Account = that.accounts[tooltipItem.index];
return account.accountNumber+":"+account.balance+"€";
}
}
}
}
Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.
Assuming your file is named myclone.csv
and contains
workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0
this code should give you an idea or two:
>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
... column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
... for h, v in zip(headers, row):
... column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>
To get your numeric values into floats, add this
converters = [str.strip] + [float] * (len(headers) - 1)
up front, and do this
for h, v, conv in zip(headers, row, converters):
column[h].append(conv(v))
for each row instead of the similar two lines above.
Gives you the list of files with full path:
Sys.glob(file.path(file_dir, "*.dbf")) ## file_dir = file containing directory
count = 0
s = "azcbobobEgghakl"
s = s.lower()
for i in range(0, len(s)):
if s[i] == 'a'or s[i] == 'e'or s[i] == 'i'or s[i] == 'o'or s[i] == 'u':
count += 1
print("Number of vowels: "+str(count))
In case you want to do it using Python: check Is it possible in python to kill process that is listening on specific port, for example 8080?
The answer from Smunk works nicely. I repeat his code here:
from psutil import process_iter
from signal import SIGTERM # or SIGKILL
for proc in process_iter():
for conns in proc.connections(kind='inet'):
if conns.laddr.port == 8080:
proc.send_signal(SIGTERM) # or SIGKILL
continue
According to the post linked in the G+ resource:
The gorgeous screen on the Nexus 10 falls into the XHDPI density bucket. On tablets, Launcher uses icons from one density bucket up [0] to render them slightly larger. To ensure that your launcher icon (arguably your apps most important asset) is crisp you need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.
So it looks like the xxhdpi is set for 480dpi. According to that, tablets use the assets from one dpi bucket higher than the one they're in for the launcher. The Nexus 10 being in bucket xhdpi will pull the launcher icon from the xxhdpi.
Also, was not aware that tablets take resources from the asset bucket above their level. Noted.
This should work in MySql
SELECT * FROM 'my_table' WHERE 'month' = MONTH(CURRENT_TIMESTAMP) AND 'year' = YEAR(CURRENT_TIMESTAMP);
Try doing this:
adb kill-server && adb start-server
(that restarts adb) Also you can try to edit an adb config file .android/adb_usb.ini
and add a line 04e8
after the header. Restart adb required for changes to take effect.
Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."
By default, all parameters are optional. The most basic approach is to simply check each one for $null
, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.
If you want to learn about all of the special support that Powershell can give you, check out these links:
I User this Code in my project, Useful for me.
private void Form1_Resize(object sender, EventArgs e)
{
int w = MainPanel.Width; // you can use form.width when you don't use panels
w = (w - 120)/4; // 120 because set 15px for each side of panels
// and put panels in FlowLayoutPanel
// 4 because i have 4 panel boxes
panel1.Width = w;
panel2.Width = w;
panel3.Width = w;
panel4.Width = w;
}
This means that the object which you are trying to access is not loaded, so write a query that makes a join fetch of the object which you are trying to access.
Eg:
If you are trying to get ObjectB from ObjectA where ObjectB is a foreign key in ObjectA.
Query :
SELECT objA FROM ObjectA obj JOIN FETCH obj.objectB objB
If you don't know the number of columns ahead of time, add each column to a list and cbind
at the end.
List <- list()
for(i in 1:n)
{
normF <- #something
List[[i]] <- normF
}
Matrix = do.call(cbind, List)
This answer does not destroy instance id, instead it is able to get current one. It also store refreshed one in Shared preferences.
Strings.xml
<string name="pref_firebase_instance_id_key">pref_firebase_instance_id</string>
<string name="pref_firebase_instance_id_default_key">default</string>
Utility.java (any class where you want to set/get preferences)
public static void setFirebaseInstanceId(Context context, String InstanceId) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor;
editor = sharedPreferences.edit();
editor.putString(context.getString(R.string.pref_firebase_instance_id_key),InstanceId);
editor.apply();
}
public static String getFirebaseInstanceId(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String key = context.getString(R.string.pref_firebase_instance_id_key);
String default_value = context.getString(R.string.pref_firebase_instance_id_default_key);
return sharedPreferences.getString(key, default_value);
}
MyFirebaseInstanceIdService.java (extends FirebaseInstanceIdService)
@Override
public void onCreate()
{
String CurrentToken = FirebaseInstanceId.getInstance().getToken();
//Log.d(this.getClass().getSimpleName(),"Inside Instance on onCreate");
String savedToken = Utility.getFirebaseInstanceId(getApplicationContext());
String defaultToken = getApplication().getString(R.string.pref_firebase_instance_id_default_key);
if(CurrentToken != null && !savedToken.equalsIgnoreCase(defaultToken))
//currentToken is null when app is first installed and token is not available
//also skip if token is already saved in preferences...
{
Utility.setFirebaseInstanceId(getApplicationContext(),CurrentToken);
}
super.onCreate();
}
@Override
public void onTokenRefresh() {
.... prev code
Utility.setFirebaseInstanceId(getApplicationContext(),refreshedToken);
....
}
Android 2.0 and above onCreate
of service is not invoked when started automatically (source). Instead onStartCommand
is overridden and used. But in actual FirebaseInstanceIdService it is declared as final and can't be overridden.
However, when we start service using startService(), if service is already running, its original instance is used (which is good). Our onCreate() (defined above) also got invoked!.
Use this in begining of MainActivity or at whichever point you think you need instance id.
MyFirebaseInstanceIdService myFirebaseInstanceIdService = new MyFirebaseInstanceIdService();
Intent intent= new Intent(getApplicationContext(),myFirebaseInstanceIdService.getClass());
//Log.d(this.getClass().getSimpleName(),"Starting MyFirebaseInstanceIdService");
startService(intent); //invoke onCreate
And Finally,
Utility.getFirebaseInstanceId(getApplicationContext())
Note, you can futher enhance this by trying to move startservice() code to getFirebaseInstanceId method.
https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...
<?php
require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
$getID3 = new getID3();
$filename="/fire/My Documents/video/ferrari1.mpg";
$fileinfo = $getID3->analyze($filename);
$width=$fileinfo['video']['resolution_x'];
$height=$fileinfo['video']['resolution_y'];
echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
echo '<pre>';print_r($fileinfo);echo '</pre>';
?>
In the new ES6 world its much easier to do a sort
numArray.sort((a,b) => a-b);
Thats all you need :)
You can use this code to get your desire output
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df
color x y
0 red 0 0
1 red 1 1
2 red 2 2
3 blue 3 9
4 blue 4 16
5 blue 5 25
To plot graph
a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)
plt.show()
Output
Use it without the greater than:
$("#panel :input");
The >
means only direct children of the element, if you want all children no matter the depth just use a space.
If the original poster was actually wanting to set an existing column to be a PRIMARY KEY
for the table and actually did not need the column to be an IDENTITY
column (two different things) then this can be done via t-SQL with:
ALTER TABLE [YourTableName]
ADD CONSTRAINT [ColumnToSetAsPrimaryKey] PRIMARY KEY ([ColumnToSetAsPrimaryKey])
Note the parenthesis around the column name after the PRIMARY KEY
option.
Although this post is old and I am making an assumption about the requestors need, I felt this additional information could be helpful to users encountering this thread as I believe the conversation could lead one to believe that an existing column can not be set to be a primary key without adding it as a new column first which would be incorrect.
i think the simple solution is:
sh /dir/* > ./result.txt
I would add to the accepted answer that you would also want to add the Accept
header to the httpClient
:
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Pygmentize is a killer tool. See this.
I combine python json.tool with pygmentize
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -l json
See the link above for pygmentize installation instruction.
A demo of this is in the image below:
It depends on the server configuration or the relevant directives session.gc_maxlifetime in php.ini
.
Typically the default is 24 minutes (1440 seconds), but your webhost may have altered the default to something else.
import os
[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text
The outer most val for sublist in ...
loop flattens the list to be one dimensional. The j
loop collects a list of every file basename and joins it to the current path. Finally, the i
loop iterates over all directories and sub directories.
This example uses the hard-coded path ./
in the os.walk(...)
call, you can supplement any path string you like.
Note: os.path.expanduser
and/or os.path.expandvars
can be used for paths strings like ~/
Its easy to add in file basename tests and directoryname tests.
For Example, testing for *.jpg
files:
... for j in i[2] if j.endswith('.jpg')] ...
Additionally, excluding the .git
directory:
... for i in os.walk('./') if '.git' not in i[0].split('/')]
Download the file from http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadjavaxservletjar.htm
Make a folder ("lib") inside the project folder and move that jar file to there.
In Eclipse, right click on project > BuildPath > Configure BuildPath > Libraries > Add External Jar
Thats all
I need to add my 5 cents. I see everybody use [
or [[
, but it worth to mention that they are not part of if syntax.
For arithmetic comparisons, use ((...))
instead.
((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.
See: ArithmeticExpression
Though it may be unrelated to your question, take a look at GetGUIThreadInfo Function.
return response(['title' => trans('web.errors.duplicate_title')], 422); //Unprocessable Entity
Hope my answer was helpful.
FLAnimatedImage is a performant open source animated GIF engine for iOS:
It's a well-tested component that I wrote to power all GIFs in Flipboard.
Try this
$(function() {
$('#clickMe').click(function(event) {
var mytext = $('#myText').val();
$('<div id="dialog">'+mytext+'</div>').appendTo('body');
event.preventDefault();
$("#dialog").dialog({
width: 600,
modal: true,
close: function(event, ui) {
$("#dialog").remove();
}
});
}); //close click
});
And in HTML
<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>
There's one more issue you might need to address if you are using the Windows 2008 Server with IIS7. The server might report the following error:
Microsoft Office Excel cannot access the file 'c:\temp\test.xls'. There are several possible reasons:
The solution is posted here (look for the text posted by user Ogawa): http://social.msdn.microsoft.com/Forums/en-US/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91?prof=required
Swift 4 with saving array types
extension Array {
func take(_ elementsCount: Int) -> [Element] {
let min = Swift.min(elementsCount, count)
return Array(self[0..<min])
}
}
HTML--
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
css--
.active{
background:red;
}
button.btn:active{
background:red;
}
jQuery--
jQuery("#my_styles .btn").click(function(){
jQuery("#my_styles .btn").removeClass('active');
jQuery(this).toggleClass('active');
});
view the live demo on jsfiddle
Different case but may help someone,
In my case Window firewall was enabled on Server,
Two thinks can be done,
1) Disable windows firewall (your on risk but it will get thing work)
2) Add port in inbound rule.
Thanks .
Jack's answer is perfectly working for click
event while longClick
is considering is as menu
button click.
By the way, if anyone is wondering how to do via kotlin,
class HomeButtonReceiver(private var context: Context,private var listener: OnHomeButtonClickListener) {
private val mFilter: IntentFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
private var mReceiver: InnerReceiver = InnerReceiver()
fun startWatch() {
context.registerReceiver(mReceiver, mFilter)
}
fun stopWatch() {
context.unregisterReceiver(mReceiver)
}
inner class InnerReceiver: BroadcastReceiver() {
private val systemDialogReasonKey = "reason"
private val systemDialogReasonHomeKey = "homekey"
override fun onReceive(context: Context?, intent: Intent?) {
val action = intent?.action
if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
val reason = intent.getStringExtra(systemDialogReasonKey)
if (reason != null && reason == systemDialogReasonHomeKey) {
listener.onHomeButtonClick()
}
}
}
}
}
SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
MAX([Value])
FOR [Period] IN ([2000], [2001], [2002])
) as pvt
Another way,
SELECT ACCOUNT,
MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account
i think this is really quick
document.querySelectorAll('body,body *').forEach(function(e) {
using DotNetZip (available as nuget package):
public void Zip(string source, string destination)
{
using (ZipFile zip = new ZipFile
{
CompressionLevel = CompressionLevel.BestCompression
})
{
var files = Directory.GetFiles(source, "*",
SearchOption.AllDirectories).
Where(f => Path.GetExtension(f).
ToLowerInvariant() != ".zip").ToArray();
foreach (var f in files)
{
zip.AddFile(f, GetCleanFolderName(source, f));
}
var destinationFilename = destination;
if (Directory.Exists(destination) && !destination.EndsWith(".zip"))
{
destinationFilename += $"\\{new DirectoryInfo(source).Name}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-ffffff}.zip";
}
zip.Save(destinationFilename);
}
}
private string GetCleanFolderName(string source, string filepath)
{
if (string.IsNullOrWhiteSpace(filepath))
{
return string.Empty;
}
var result = filepath.Substring(source.Length);
if (result.StartsWith("\\"))
{
result = result.Substring(1);
}
result = result.Substring(0, result.Length - new FileInfo(filepath).Name.Length);
return result;
}
Usage:
Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest");
Or
Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest\output.zip");
In case you need values sorted, this works (Swift 4)
let sortedValues = Array(Set(array)).sorted()
When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.
Open Arduino IDE and go to files and click on the preference in the Arduino IDE.
Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.
Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.
You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.
You can use generics with the following trick (casting to anonymous type):
public void LogEmployees<T>(IEnumerable<T> list)
{
foreach (T item in list)
{
var typedItem = Cast(item, new { Name = "", Id = 0 });
// now you can use typedItem.Name, etc.
}
}
static T Cast<T>(object obj, T type)
{
return (T)obj;
}
How to rotate an image around its center:
ImageView view = ... //Initialize ImageView via FindViewById or programatically
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//Setup anim with desired properties
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE); //Repeat animation indefinitely
anim.setDuration(700); //Put desired duration per anim cycle here, in milliseconds
//Start animation
view.startAnimation(anim);
//Later on, use view.setAnimation(null) to stop it.
This will cause the image to rotate around its center (0.5 or 50% of its width/height). I am posting this for future readers who get here from Google, as I have, and who wish to rotate the image around its center without defining said center in absolute pixels.
I think that more accurate is this syntax:
SELECT CONVERT(CHAR(10), GETDATE(), 103)
I add SELECT and GETDATE() for instant testing purposes :)
It is working form me. Here I am geeting the table created datetime and adding 10 minutes on the datetime. later depending on the current time, Expiry Operations are done.
from datetime import datetime, time, timedelta
import pytz
Added 10 minutes on database datetime
table_datetime = '2019-06-13 07:49:02.832969' (example)
# Added 10 minutes on database datetime
# table_datetime = '2019-06-13 07:49:02.832969' (example)
table_expire_datetime = table_datetime + timedelta(minutes=10 )
# Current datetime
current_datetime = datetime.now()
# replace the timezone in both time
expired_on = table_expire_datetime.replace(tzinfo=utc)
checked_on = current_datetime.replace(tzinfo=utc)
if expired_on < checked_on:
print("Time Crossed)
else:
print("Time not crossed ")
It worked for me.
You should be able to create a query with this filter here:
(&(objectClass=user)(sAMAccountName=yourUserName)
(memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))
and when you run that against your LDAP server, if you get a result, your user "yourUserName" is indeed a member of the group "CN=YourGroup,OU=Users,DC=YourDomain,DC=com
Try and see if this works!
If you use C# / VB.Net and System.DirectoryServices, this snippet should do the trick:
DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=yourcompany,dc=com");
DirectorySearcher srch = new DirectorySearcher(rootEntry);
srch.SearchScope = SearchScope.Subtree;
srch.Filter = "(&(objectClass=user)(sAMAccountName=yourusername)(memberOf=CN=yourgroup,OU=yourOU,DC=yourcompany,DC=com))";
SearchResultCollection res = srch.FindAll();
if(res == null || res.Count <= 0) {
Console.WriteLine("This user is *NOT* member of that group");
} else {
Console.WriteLine("This user is INDEED a member of that group");
}
Word of caution: this will only test for immediate group memberships, and it will not test for membership in what is called the "primary group" (usually "cn=Users") in your domain. It does not handle nested memberships, e.g. User A is member of Group A which is member of Group B - that fact that User A is really a member of Group B as well doesn't get reflected here.
Marc
Here is a use case for AtomicReference:
Consider this class that acts as a number range, and uses individual AtmomicInteger variables to maintain lower and upper number bounds.
public class NumberRange {
// INVARIANT: lower <= upper
private final AtomicInteger lower = new AtomicInteger(0);
private final AtomicInteger upper = new AtomicInteger(0);
public void setLower(int i) {
// Warning -- unsafe check-then-act
if (i > upper.get())
throw new IllegalArgumentException(
"can't set lower to " + i + " > upper");
lower.set(i);
}
public void setUpper(int i) {
// Warning -- unsafe check-then-act
if (i < lower.get())
throw new IllegalArgumentException(
"can't set upper to " + i + " < lower");
upper.set(i);
}
public boolean isInRange(int i) {
return (i >= lower.get() && i <= upper.get());
}
}
Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. This can be fixed by using a AtomicReference instead of using individual AtomicIntegers for upper and lower bounds.
public class CasNumberRange {
// Immutable
private static class IntPair {
final int lower; // Invariant: lower <= upper
final int upper;
private IntPair(int lower, int upper) {
this.lower = lower;
this.upper = upper;
}
}
private final AtomicReference<IntPair> values =
new AtomicReference<IntPair>(new IntPair(0, 0));
public int getLower() {
return values.get().lower;
}
public void setLower(int lower) {
while (true) {
IntPair oldv = values.get();
if (lower > oldv.upper)
throw new IllegalArgumentException(
"Can't set lower to " + lower + " > upper");
IntPair newv = new IntPair(lower, oldv.upper);
if (values.compareAndSet(oldv, newv))
return;
}
}
public int getUpper() {
return values.get().upper;
}
public void setUpper(int upper) {
while (true) {
IntPair oldv = values.get();
if (upper < oldv.lower)
throw new IllegalArgumentException(
"Can't set upper to " + upper + " < lower");
IntPair newv = new IntPair(oldv.lower, upper);
if (values.compareAndSet(oldv, newv))
return;
}
}
}
myDataTable.Columns.Contains("col_name")
One of the simplest ways to convert the categorical variable into dummy/indicator variables is to use get_dummies provided by pandas.
Say for example we have data in which sex
is a categorical value (male & female)
and you need to convert it into a dummy/indicator here is how to do it.
tranning_data = pd.read_csv("../titanic/train.csv")
features = ["Age", "Sex", ] //here sex is catagorical value
X_train = pd.get_dummies(tranning_data[features])
print(X_train)
Age Sex_female Sex_male
20 0 1
33 1 0
40 1 0
22 1 0
54 0 1
_x000D_
I just tried all of these, and for IE11, the only thing that seems to work is disabled="true". Values of disabled or no value given didnt work. As a matter of fact, the jsp got an error that equal is required for all fields, so I had to specify disabled="true" for this to work.
echo "this is the body" | mail -s "this is the subject" "to@address"
Depends on what type of button you are using
<input type='button' value='Add' id='btnAddProfile'>
$("#btnAddProfile").attr('value', 'Save'); //versions older than 1.6
<input type='button' value='Add' id='btnAddProfile'>
$("#btnAddProfile").prop('value', 'Save'); //versions newer than 1.6
<!-- Different button types-->
<button id='btnAddProfile' type='button'>Add</button>
$("#btnAddProfile").html('Save');
Your button could also be a link. You'll need to post some HTML for a more specific answer.
EDIT : These will work assuming you've wrapped it in a .click()
call, of course
EDIT 2 : Newer jQuery versions (from > 1.6) use .prop
rather than .attr
EDIT 3 : If you're using jQuery UI, you need to use DaveUK's method (below) of adjusting the text property
This will allow a space between the two columns and obviously if you want to change the default width you can go for mixins to modify the default bootstrap width. Or, you can give the width using the inline CSS style.
<div class="col-md-5 pull-left"></div>
<div class="col-md-5 pull-right"></div>
See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)
1. You might also use EXIT_ON_CLOSE
, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.
The 'button' to invoke this operation is already on a frame.
DISPOSE_ON_CLOSE
functionality.A much better way is to use inline-block
, because you don't need to use clear:both
at the end of your list anymore.
Try this:
<ul>
<li>
<a href="#">some item</a>
</li>
<li>
<a href="#">another item</a>
</li>
</ul>
CSS:
ul > li{
display:inline-block;
}
Have a look at it here : http://jsfiddle.net/shahverdy/4N6Ap/
In my case in php.ini
[CLDbg]
extension=php_cl_dbg_5_3_VC9.dll
clport=6000
I removed Codelobster which support different PHP version, so need to update to:
[CLDbg]
;extension=php_cl_dbg_5_3_VC9.dll
;clport=6000
Without resorting gridspec entirely, the following might also be used to remove the gaps by setting wspace and hspace to zero:
import matplotlib.pyplot as plt
plt.clf()
f, axarr = plt.subplots(4, 4, gridspec_kw = {'wspace':0, 'hspace':0})
for i, ax in enumerate(f.axes):
ax.grid('on', linestyle='--')
ax.set_xticklabels([])
ax.set_yticklabels([])
plt.show()
plt.close()
Resulting in:
$('#myLink').click(function(e) {
e.preventDefault();
//do other stuff when a click happens
});
That will prevent the default behaviour of a hyperlink, which is to visit the specified href.
From the jQuery tutorial:
For click and most other events, you can prevent the default behaviour - here, following the link to jquery.com - by calling event.preventDefault() in the event handler
If you want to preventDefault()
only if a certain condition is fulfilled (something is hidden for instance), you could test the visibility of your ul with the class expanded. If it is visible (i.e. not hidden) the link should fire as normal, as the if statement will not be entered, and thus the default behaviour will not be prevented:
$('ul li').click(function(e) {
if($('ul.expanded').is(':hidden')) {
e.preventDefault();
$('ul').addClass('expanded');
$('ul.expanded').fadeIn(300);
}
});
If you are using “import android.app.Fragment;” Then use either:
1)
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.specific_function_name();
Where R.id.example_fragment is most likely the FrameLayout id inside your xml layout. OR
2)
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentByTag(“FragTagName”);
fragment.specific_function_name();
Where FragTagName is the name u specified when u did:
TabHost mTabHost.newTabSpec(“FragTagName”)
If you are using “import android.support.v4.app.Fragment;” Then use either:
1)
ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.example_fragment);
fragment.specific_function_name();
OR
2)
ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentByTag(“FragTagName”);
fragment.specific_function_name();
Query :
$sqlQuery = "UPDATE
update_table
SET
set_name = 'value'
WHERE
where_name = 'name'
LIMIT 1;";
PHP function:
function updateAndGetId($sqlQuery)
{
mysql_query(str_replace("SET", "SET id = LAST_INSERT_ID(id),", $sqlQuery));
return mysql_insert_id();
}
It's work for me ;)
Notepad++ only has column editing. This is not completely the same as multiple cursors.
Sublime Text has a marvelous implementation of this, might be worth checking out...
It's a relatively new editor (2011) that is gaining popularity quite fast:
http://www.google.com/trends/explore#q=Notepad%2B%2B%2C%20Sublime%20Text&cmpt=q
Edit: Apparently somewhere around Notepad++ version 6.x multi-cursor editing got added, but there are still a few more advanced features for it in Sublime, like "select next occurrence".
You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.
An example:
width: calc((100%) - (32px))
Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.
.outer {_x000D_
width: 200px;_x000D_
height: 120px;_x000D_
background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
height: 40px;_x000D_
top: 30px;_x000D_
position: relative;_x000D_
padding: 16px;_x000D_
background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
<div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
<div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
Java 9
public static void main(String[] args) {
Map<Integer,String> map = Map.ofEntries(entry(1,"A"), entry(2,"B"), entry(3,"C"));
}
- There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?
noexcept
is tricky, as it is part of the functions interface. Especially, if you are writing a library, your client code can depend on the noexcept
property. It can be difficult to change it later, as you might break existing code. That might be less of a concern when you are implementing code that is only used by your application.
If you have a function that cannot throw, ask yourself whether it will like stay noexcept
or would that restrict future implementations? For example, you might want to introduce error checking of illegal arguments by throwing exceptions (e.g., for unit tests), or you might depend on other library code that could change its exception specification. In that case, it is safer to be conservative and omit noexcept
.
On the other hand, if you are confident that the function should never throw and it is correct that it is part of the specification, you should declare it noexcept
. However, keep in mind that the compiler will not be able to detect violations of noexcept
if your implementation changes.
- For which situations should I be more careful about the use of noexcept, and for which situations can I get away with the implied noexcept(false)?
There are four classes of functions that should you should concentrate on because they will likely have the biggest impact:
noexcept(true)
unless you make them noexcept(false)
)These functions should generally be noexcept
, and it is most likely that library implementations can make use of the noexcept
property. For example, std::vector
can use non-throwing move operations without sacrificing strong exception guarantees. Otherwise, it will have to fall back to copying elements (as it did in C++98).
This kind of optimization is on the algorithmic level and does not rely on compiler optimizations. It can have a significant impact, especially if the elements are expensive to copy.
- When can I realistically expect to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.
The advantage of noexcept
against no exception specification or throw()
is that the standard allows the compilers more freedom when it comes to stack unwinding. Even in the throw()
case, the compiler has to completely unwind the stack (and it has to do it in the exact reverse order of the object constructions).
In the noexcept
case, on the other hand, it is not required to do that. There is no requirement that the stack has to be unwound (but the compiler is still allowed to do it). That freedom allows further code optimization as it lowers the overhead of always being able to unwind the stack.
The related question about noexcept, stack unwinding and performance goes into more details about the overhead when stack unwinding is required.
I also recommend Scott Meyers book "Effective Modern C++", "Item 14: Declare functions noexcept if they won't emit exceptions" for further reading.
Now W3c provides an official difference on their site:
Java converts Integer to int and back automatically (unless you are still with Java 1.4).
This path worked for me. on a 32 bit machine.
C:\Windows\System32\mmc.exe /32 C:\Windows\system32\SQLServerManager10.msc
I'm going to attempt to explain this without making any mistakes, but I'm betting this will attract a clarification or two in the comments.
A data frame is a list. When you subset a data frame using the name of a column and [
, what you're getting is a sublist (or a sub data frame). If you want the actual atomic column, you could use [[
, or somewhat confusingly (to me) you could do aframe[,2]
which returns a vector, not a sublist.
So try running this sequence and maybe things will be clearer:
avector <- as.vector(aframe['a2'])
class(avector)
avector <- aframe[['a2']]
class(avector)
avector <- aframe[,2]
class(avector)
On the replacement side, you must use $1, not \1.
And you can only do what you want by making replace an evalable expression that gives the result you want and telling s/// to eval it with the /ee modifier like so:
$find="start (.*) end";
$replace='"foo $1 bar"';
$var = "start middle end";
$var =~ s/$find/$replace/ee;
print "var: $var\n";
To see why the "" and double /e are needed, see the effect of the double eval here:
$ perl
$foo = "middle";
$replace='"foo $foo bar"';
print eval('$replace'), "\n";
print eval(eval('$replace')), "\n";
__END__
"foo $foo bar"
foo middle bar
(Though as ikegami notes, a single /e or the first /e of a double e isn't really an eval()
; rather, it tells the compiler that the substitution is code to compile, not a string. Nonetheless, eval(eval(...))
still demonstrates why you need to do what you need to do to get /ee to work as desired.)
The Python standard library does provide sched and threading for this task. But this means your scheduler script will have be running all the time instead of leaving its execution to the OS, which may or may not be what you want.
If the input value gets populated by a script that has some latency involved (e.g. AJAX call) then you need to wait until the input has been populated. E.g.
var w = new WebDriverWait(WebBrowser, TimeSpan.FromSeconds(10));
w.Until((d) => {
// Wait until the input has a value...
var elements = d.FindElements(By.Name(name));
var ele = elements.SingleOrDefault();
if (ele != null)
{
// Found a single element
if (ele.GetAttribute("value") != "")
{
// We have a value now
return true;
}
}
return false;
});
var e = WebBrowser.Current.FindElement(By.Name(name));
if (e.GetAttribute("value") != value)
{
Assert.Fail("Result contains a field named '{0}', but its value is '{1}', not '{2}' as expected", name, e.GetAttribute("value"), value);
}
From Creating Pipes in C, this shows you how to fork a program to use a pipe. If you don't want to fork(), you can use named pipes.
In addition, you can get the effect of prog1 | prog2
by sending output of prog1
to stdout and reading from stdin
in prog2
. You can also read stdin by opening a file named /dev/stdin
(but not sure of the portability of that).
/*****************************************************************************
Excerpt from "Linux Programmer's Guide - Chapter 6"
(C)opyright 1994-1995, Scott Burkett
*****************************************************************************
MODULE: pipe.c
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
I had this problem because a dll I was using had Sqlite as a dependency (configured in NuGet with only the Sqlite core package.). The project compiles and copies all the Sqlite dll-s except the 'SQLite.Interop.dll' (both x86 and x64 folder).
The solution was very simple: just add the System.Data.SQLite.Core package as a dependency (with NuGet) to the project you are building/running and the dll-s will be copied.
instant/feasible/partial answer : https://stackoverflow.com/a/20130959/2584794
unlike from the previous answer where netstat -a -o -n was used incredibly long list was to be looked into without the name of application using those ports
In python the with
keyword is used when working with unmanaged resources (like file streams). It is similar to the using
statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally
blocks.
From Python Docs:
The
with
statement clarifies code that previously would usetry...finally
blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.The
with
statement is a control-flow structure whose basic structure is:with expression [as variable]: with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has
__enter__()
and__exit__()
methods).
Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with
with using
.
In my case, there was no string on which i was calling appendChild
, the object i was passing on appendChild
argument was wrong, it was an array and i had pass an element object, so i used divel.appendChild(childel[0])
instead of divel.appendChild(childel)
and it worked. Hope it help someone.
Application Class:
import android.app.Application;
import android.content.Context;
public class MyApplication extends Application {
private static Context mContext;
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getAppContext() {
return mContext;
}
}
Declare the Application in the AndroidManifest:
<application android:name=".MyApplication"
...
/>
Usage:
MyApplication.getAppContext()
You can follow this approach:
void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
int val;
if (dic.TryGetValue(key, out val))
{
// yay, value exists!
dic[key] = val + newValue;
}
else
{
// darn, lets add the value
dic.Add(key, newValue);
}
}
The edge you get here is that you check and get the value of corresponding key in just 1 access to the dictionary.
If you use ContainsKey
to check the existance and update the value using dic[key] = val + newValue;
then you are accessing the dictionary twice.
The specific problem is that you're declaring a new variable instead of assigning to an existing one:
char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this
and trying to compare string values by comparing pointers:
if (array!="") // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string
although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.
The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::string
and it will manage all the memory allocation for you:
std::string appendCharToString(std::string const & s, char a) {
return s + a;
}
"A picture is worth a thousand words".
I have a simple example here, it's similar to your case.
string s1 = "abc";
string s2 = s1;
s1 = "def";
Console.WriteLine(s2);
// Output: abc
This is what happened:
s1
and s2
variables reference to the same "abc"
string object."abc"
string object do not modify itself (to "def"
), but a new "def"
string object is created instead, and then s1
references to it.s2
still references to "abc"
string object, so that's the output.You can use dict.get()
value = d.get(key)
which will return None
if key is not in d
. You can also provide a different default value that will be returned instead of None
:
value = d.get(key, "empty")
Most guides I've seen suggest that you should use
if A:
unless you have a reason to be more specific.
There are some slight differences. There are values other than None that return False, for example empty lists, or 0, so have a think about what it is you're really testing for.
For adding background icon always before text when length of text is not known in advance.
.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value)
no add(value)
.
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
MS SQL 2008 can also use the string version of true or false...
select * from users where active = 'true'
-- or --
select * from users where active = 'false'
On Linux, macOS and Unix to display the groups to which you belong, use:
id -Gn
which is equivalent to groups
utility which has been obsoleted on Unix (as per Unix manual).
On macOS and Unix, the command id -p
is suggested for normal interactive.
Explanation of the parameters:
-G
,--groups
- print all group IDs
-n
,--name
- print a name instead of a number, for-ugG
-p
- Make the output human-readable.
Just getting the name from scm.branches
is not enough if you've used a build parameter as a branch specifier, e.g. ${BRANCH}
.
You need to expand that string into a real name:
scm.branches.first().getExpandedName(env.getEnvironment())
Note that getEnvironment()
must be an explicit getter otherwise env
will look up for an environment variable called environment.
Don't forget that you need to approve those methods to make them accessible from the sandbox.
int foo::i = 0;
Is the correct syntax for initializing the variable, but it must go in the source file (.cpp) rather than in the header.
Because it is a static variable the compiler needs to create only one copy of it. You have to have a line "int foo:i" some where in your code to tell the compiler where to put it otherwise you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker.
I think you lack to pass Connection
object to your command
object. and it is much better if you will use command
and parameters
for that.
using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection; // <== lacking
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
command.Parameters.AddWithValue("@staffName", name);
command.Parameters.AddWithValue("@userID", userId);
command.Parameters.AddWithValue("@idDepart", idDepart);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close();
}
}
}
The SQL used in a PreparedStatement is precompiled on the driver. From that point on, the parameters are sent to the driver as literal values and not executable portions of SQL; thus no SQL can be injected using a parameter. Another beneficial side effect of PreparedStatements (precompilation + sending only parameters) is improved performance when running the statement multiple times even with different values for the parameters (assuming that the driver supports PreparedStatements) as the driver does not have to perform SQL parsing and compilation each time the parameters change.
running your code hundred times may affect the camera to function wrongly.Your activity may be performing correctly but system could not buy it.so camera forces stop. One main tip all missed is rebooting your phone and not only eclipse..It worked for me..
Yes there are two way to add a line feed:
Use the existing function from VBA vbCrLf
in the string you want to add a line feed, as such:
Dim text As String
text = "Hello" & vbCrLf & "World!"
Worksheets(1).Cells(1, 1) = text
Use the Chr()
function and pass the ASCII characters 13 and 10 in order to add a line feed, as shown bellow:
Dim text As String
text = "Hello" & Chr(13) & Chr(10) & "World!"
Worksheets(1).Cells(1, 1) = text
In both cases, you will have the same output in cell (1,1) or A1.
Why didn't it work for you using Deferred Objects
? Unless I misunderstood something this may work for you.
/* AJAX success handler */
var echo = function() {
console.log('Pass1');
};
var pass = function() {
$.when(
/* AJAX requests */
$.post("/echo/json/", { delay: 1 }, echo),
$.post("/echo/json/", { delay: 2 }, echo),
$.post("/echo/json/", { delay: 3 }, echo)
).then(function() {
/* Run after all AJAX */
console.log('Pass2');
});
};?
Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async
to false
in your $.ajax
requests to make them blocking. This will hang your browser until the request is finished though.
Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.
I want to select the distinct values from one column 'GrondOfLucht' but they should be sorted in the order as given in the column 'sortering'. I cannot get the distinct values of just one column using
Select distinct GrondOfLucht,sortering
from CorWijzeVanAanleg
order by sortering
It will also give the column 'sortering' and because 'GrondOfLucht' AND 'sortering' is not unique, the result will be ALL rows.
use the GROUP to select the records of 'GrondOfLucht' in the order given by 'sortering
SELECT GrondOfLucht
FROM dbo.CorWijzeVanAanleg
GROUP BY GrondOfLucht, sortering
ORDER BY MIN(sortering)
One possible situation where this might be needed:
If you are using finally
block to close connections but in the try
block, the program exits with sys.exit()
before the connection is defined. In this case, the finally
block will be called and the connection closing statement will fail since no connection was created.
You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true
.
You can also add multiple hidden fields. Use this way:
CustomizePPT.setHiddenFields(
{
"hidden" :
{
'fieldinFORM' : 'thisdata201' ,
'fieldinFORM2' : 'this3' //multiple hidden fields
.
.
.
.
.
'nNoOfFields' : 'nthData'
},
"form" :
{
"status" : "true",
"formID" : "form3"
}
} );
var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
var request = [];_x000D_
var container = '';_x000D_
console.log(arguments);_x000D_
request = arguments[0].hidden;_x000D_
console.log(arguments[0].hasOwnProperty('form'));_x000D_
if(arguments[0].hasOwnProperty('form') == true)_x000D_
{_x000D_
if(arguments[0].form.status == 'true'){_x000D_
var parent = document.getElementById("container");_x000D_
container = document.createElement('form');_x000D_
parent.appendChild(container);_x000D_
Object.assign(container, {'id':arguments[0].form.formID});_x000D_
}_x000D_
}_x000D_
else{_x000D_
container = document.getElementById("container");_x000D_
}_x000D_
_x000D_
//var container = document.getElementById("container");_x000D_
Object.keys(request).forEach(function(elem)_x000D_
{_x000D_
if($('#'+elem).length <= 0){_x000D_
console.log("Hidden Field created");_x000D_
var input = document.createElement('input');_x000D_
Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
container.appendChild(input);_x000D_
}else{_x000D_
console.log("Hidden Field Exists and value is below" );_x000D_
$('#'+elem).val(request[elem]);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
_x000D_
</div>
_x000D_
In my case, HAXM was already installed in SDK Manager. But every time I attempted to intelhaxm-android.exe, it would silently fail.
Finally, I extracted the internal installers out of intelhaxm-android.exe in 7-zip. Copied the three files to another directory and finally got a real installer to run. Ran without a hitch and HAXM issues were gone.
For a lot of projects, there is actually 0% difference between the different pythons in terms of speed. That is those that are dominated by engineering time and where all pythons have the same amount of library support.
Using the DateTime class available in PHP version 5.2 it would be done like this:
$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');
As of PHP 5.4 you can do this as a one-liner:
echo (new DateTime('17 Oct 2008'))->format('c');
https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For <a>
elements, omit data-target, and use href="#modalID"
instead.
Actually GitHub does not create an empty folder.
For example, to create a folder in C:\Users\Username\Documents\GitHub\Repository
:
Create a folder named docs
Create a file name index.html
under docs
Open the GitHub for desktop application
It will automatically sync, and it will be there.
Other solution can be
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.setType("plain/text");
emailIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Yo");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi");
startActivity(emailIntent);
Assuming most of the android device has GMail app already installed.
Why not write a piece of code like:
int max_neg = ~(1 << 31);
int all_ones = -1;
int max_pos = all_ones & max_neg;
I also faced the same problem and the problem was that the libraries were missing in some of the following files.
settings.gradle, app/build.gradle, package.json, MainApplication.java
Suppose the library is react-native-vector-icons then it should be mentioned in following files;
compile project(':react-native-vector-icons')
include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
Import the dependency: import com.oblador.vectoricons.VectorIconsPackage;
and then add: new VectorIconsPackage() in getPackages() method.
foreach($display_related_tags as $key => $tag_name)
{
if($tag_name == $found_tag['name'])
unset($display_related_tags[$key];
}
I've done this kind of thing with a form that contains a TextBox.
So if you wanted to put this in say cell H1
, then use:
ActiveSheet.Range("H1").Value = txtBoxName.Text
Webapp server may keep a thread pool, and a ThreadLocal
var should be removed before response to the client, thus current thread may be reused by next request.
Objects in python store their atributes (including functions) in a dict called __dict__
. You can (but generally shouldn't) use this to access the attributes directly. If you just want a list, you can also call dir(obj)
, which returns an iterable with all the attribute names, which you could then pass to getattr
.
However, needing to do anything with the names of the variables is usually bad design. Why not keep them in a collection?
class Foo(object):
def __init__(self, **values):
self.special_values = values
You can then iterate over the keys with for key in obj.special_values:
you need to enable the openssl extension in
C:\wamp\bin\php\php5.4.12\php.ini
that is the php configuration file that has it type has "configuration settings" with a driver-notepad like icon.
there is a semi-colon before the openssl extension
;extension=php_openssl.dll
remove the semi-colon and you'll have
extension=php_openssl.dll
I have what I believe is a better solution than the $('html, body')
hack.
It's not a one-liner, but the issue I had with $('html, body')
is that if you log $(window).scrollTop()
during the animation, you'll see that the value jumps all over the place, sometimes by hundreds of pixels (though I don't see anything like that happening visually). I needed the value to be predictable, so that I could cancel the animation if the user grabbed the scroll bar or twirled the mousewheel during the auto-scroll.
Here is a function will animate scrolling smoothly:
function animateScrollTop(target, duration) {
duration = duration || 16;
var scrollTopProxy = { value: $(window).scrollTop() };
if (scrollTopProxy.value != target) {
$(scrollTopProxy).animate(
{ value: target },
{ duration: duration, step: function (stepValue) {
var rounded = Math.round(stepValue);
$(window).scrollTop(rounded);
}
});
}
}
Below is a more complex version that will cancel the animation on user interaction, as well as refiring until the target value is reached, which is useful when trying to set the scrollTop instantaneously (e.g. simply calling $(window).scrollTop(1000)
— in my experience, this fails to work about 50% of the time.)
function animateScrollTop(target, duration) {
duration = duration || 16;
var $window = $(window);
var scrollTopProxy = { value: $window.scrollTop() };
var expectedScrollTop = scrollTopProxy.value;
if (scrollTopProxy.value != target) {
$(scrollTopProxy).animate(
{ value: target },
{
duration: duration,
step: function (stepValue) {
var roundedValue = Math.round(stepValue);
if ($window.scrollTop() !== expectedScrollTop) {
// The user has tried to scroll the page
$(scrollTopProxy).stop();
}
$window.scrollTop(roundedValue);
expectedScrollTop = roundedValue;
},
complete: function () {
if ($window.scrollTop() != target) {
setTimeout(function () {
animateScrollTop(target);
}, 16);
}
}
}
);
}
}
p = {1,2,3} is wrong.
You can never use this:
int * p;
p = {1,2,3};
loop is right
int *p,i;
p = malloc(3*sizeof(int));
for(i = 0; i<3; ++i)
p[i] = i;
I have had a similar problem before where it turned out to be the web brower (chrome in my case) that was the issue.
If you are using chrome, try launching it so:
For Windows:
1) Create a shortcut to Chrome on your desktop. Right-click on the shortcut and choose Properties, then switch to “Shortcut” tab.
2) In the “Target” field, append the following: –args –disable-web-security
For Mac, Open a terminal window and run this from command-line: open ~/Applications/Google\ Chrome.app/ –args –disable-web-security
Above info from:
Let me give some information on them:
quit()
simply raises the SystemExit
exception.
Furthermore, if you print it, it will give a message:
>>> print (quit)
Use quit() or Ctrl-Z plus Return to exit
>>>
This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit
.
Nevertheless, quit
should not be used in production code. This is because it only works if the site
module is loaded. Instead, this function should only be used in the interpreter.
exit()
is an alias for quit
(or vice-versa). They exist together simply to make Python more user-friendly.
Furthermore, it too gives a message when printed:
>>> print (exit)
Use exit() or Ctrl-Z plus Return to exit
>>>
However, like quit
, exit
is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site
module.
sys.exit()
also raises the SystemExit
exception. This means that it is the same as quit
and exit
in that respect.
Unlike those two however, sys.exit
is considered good to use in production code. This is because the sys
module will always be there.
os._exit()
exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork
.
Note that, of the four methods given, only this one is unique in what it does.
Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit
.
Or, even better in my opinion, you can just do directly what sys.exit
does behind the scenes and run:
raise SystemExit
This way, you do not need to import sys
first.
However, this choice is simply one on style and is purely up to you.
Hat tip to Adam Bien if you don't want to use createQuery
with a String
and want type safety:
@PersistenceContext EntityManager em; public List<ConfigurationEntry> allEntries() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class); Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class); CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry); TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all); return allQuery.getResultList(); }
http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as
for me replace doesn't work... try this code:
str = str.split(""").join('"');
To do it in LINQ to Entities, you have to use supported methods:
var year = someDate.Year;
var month = ...
var q = from r in Context.Records
where Microsoft.VisualBasic.DateAndTime.Year(r.SomeDate) == year
&& // month and day
Ugly, but it works, and it's done on the DB server.
rather than doing complicated stuff, copy your repo (on your computer) to another place. delete the large file. do a couple of push and pull. Then some of your files will be messed up having things like "<<<<<< HEAD". Just copy your backup into the old folder on the disk. Do another add, commit, push!
The main reason to avoid using the matrix
class is that a) it's inherently 2-dimensional, and b) there's additional overhead compared to a "normal" numpy array. If all you're doing is linear algebra, then by all means, feel free to use the matrix class... Personally I find it more trouble than it's worth, though.
For arrays (prior to Python 3.5), use dot
instead of matrixmultiply
.
E.g.
import numpy as np
x = np.arange(9).reshape((3,3))
y = np.arange(3)
print np.dot(x,y)
Or in newer versions of numpy, simply use x.dot(y)
Personally, I find it much more readable than the *
operator implying matrix multiplication...
For arrays in Python 3.5, use x @ y
.
Another simple way to hack it:
seq 20 | xargs -Iz echo "Hi there"
run echo 20 times.
Notice that seq 20 | xargs -Iz echo "Hi there z"
would output:
Hi there 1
Hi there 2
...
ShellEd looks promising, does syntax highlighting, and has positive reviews, although I've not tried it myself. It was approved for distro inclusion by Redhat. There's a little more info on the ShellEd plugin page on the Eclipse site, and installation instructions on their wiki.
Note that if you're not running an up-to-date version of Eclipse (as of this writing, Juno) you'll need to use an older version, for instance 2.0.1 is compatible with Indigo.
Sounds like you're working in just one table so something like this:
update your_table
set B = A
where B is null
Your time string is similar to the time format in rfc 2822 (date format in email, http headers). You could parse it using only stdlib:
>>> from email.utils import parsedate_tz
>>> parsedate_tz('Tue Jun 22 07:46:22 EST 2010')
(2010, 6, 22, 7, 46, 22, 0, 1, -1, -18000)
See solutions that yield timezone-aware datetime objects for various Python versions: parsing date with timezone from an email.
In this format, EST
is semantically equivalent to -0500
. Though, in general, a timezone abbreviation is not enough, to identify a timezone uniquely.
In addition to the excellent answers above, the following shows how to add text to each page of a multi-page document:
using (var reader = new PdfReader(@"C:\Input.pdf"))
{
using (var fileStream = new FileStream(@"C:\Output.pdf", FileMode.Create, FileAccess.Write))
{
var document = new Document(reader.GetPageSizeWithRotation(1));
var writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
for (var i = 1; i <= reader.NumberOfPages; i++)
{
document.NewPage();
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
var importedPage = writer.GetImportedPage(reader, i);
var contentByte = writer.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 12);
var multiLineString = "Hello,\r\nWorld!".Split('\n');
foreach (var line in multiLineString)
{
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
}
contentByte.EndText();
contentByte.AddTemplate(importedPage, 0, 0);
}
document.Close();
writer.Close();
}
}
yourbox {
position: absolute;
left: 100%;
top: 0;
}
left:100%; is the important issue here!
What are the target browsers? Different browsers set different default CSS rules. Try including a CSS reset, such as the meyerweb CSS reset or normalize.css, to remove those defaults. Google "CSS reset vs normalize" to see the differences.
Can I pass parameters by reference in Java?
No.
Why ? Java has only one mode of passing arguments to methods: by value.
Note:
For primitives this is easy to understand: you get a copy of the value.
For all other you get a copy of the reference and this is called also passing by value.
It is all in this picture:
Convert binary file to base64 & vice versa. Prove in python 3.5.2
import base64
read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()
b64 = base64.b64encode(data)
print (b64)
# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)
# Test in python 3.5.2
That is a default behaviour of each browser; your browser seems to be Safari, in Google Chrome it is orange in color!
Use this to remove this effect:
button {
outline: none; // this one
}
Are you trying to submit a form?
Listen to the submit
event instead.
This will handle click
and enter
.
If you must use enter key...
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
If you are trying to make more than just one folder on the root of the sdcard,
ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"
then instead of folder.mkdir()
you would use folder.mkdirs()
I've made this mistake in the past & I took forever to figure it out.
Stumbled across this today in a search for answers and I thought I'd add my version to the list (No pun intended). It utlises the null conditional operator of c#6.0
IEnumerable<Item> collection = GetTheCollection();
var index = collection
.Select((item,idx) => new { Item = item, Index = idx })
//or .FirstOrDefault(_ => _.Item.Prop == something)
.FirstOrDefault(_ => _.Item == itemToFind)?.Index ?? -1;
I've done some 'racing of the old horses' (testing) and for large collections (~100,000), worst case scenario that item you want is at the end, this is 2x faster than doing ToList().FindIndex()
. If the Item you want is in the middle its ~4x faster.
For smaller collections (~10,000) it seems to be only marginally faster
Heres how I tested it https://gist.github.com/insulind/16310945247fcf13ba186a45734f254e
It "maps" a function to each item in an Enumerable
- in this case, a range. So it would call the block passed once for every integer from 0 to param_count
(exclusive - you're right about the dots) and return an array containing each return value.
Here's the documentation for Enumerable#map
. It also has an alias, collect
.
It could be because of couple of Browser settings. Try with these options checked..
Tools > Internet Options > Advanced > Enable Integrated Windows Authentication (works with Integrated Windows Authentication set on IIS)
Tools > Internet Options> Security > Local Intranet > Custom Level > Automatic Logon
Worst case, try adding localhost to the Trusted sites.
If you are in a network, you can also try debugging by getting a network trace. Could be because of some proxy trying to authenticate.
There are a number of ways to make Python speak in both Python3 and Python2, two great methods are:
If you are on mac you will have the os module built into your computer. You can import the os module using:
import os
You can then use os to run terminal commands using the os.system command:
os.system("Your terminal")
In terminal, the way you make your computer speak is using the "say" command, thus to make the computer speak you simply use:
os.system("say 'some text'")
If you want to use this to speak a variable you can use:
os.system("say " + myVariable)
The second way to get python to speak is to use
You will have to install this using
pip isntall pyttsx3
or for Python3
pip3 install pyttsx3
You can then use the following code to get it to speak:
import pyttsx3
engine = pyttsx3.init()
engine.say("Your Text")
engine.runAndWait()
I hope this helps! :)
As others have suggested that you should look into MERGE statement but nobody provided a solution using it I'm adding my own answer with this particular TSQL construct. I bet you'll like it.
Your code has a typo in your if
statement in not exists(select...)
part. Inner select
statement has only one where
condition while UserName condition is excluded from the not exists
due to invalid brace completion. In any case you cave too many closing braces.
I assume this based on the fact that you're using two where
conditions in update
statement later on in your code.
Let's continue to my answer...
MERGE statement is a beautiful TSQL gem very well suited for "insert or update" situations. In your case it would look similar to the following code. Take into consideration that I'm declaring variables what are likely stored procedure parameters (I suspect).
declare @clockDate date = '08/10/2012';
declare @userName = 'test';
merge Clock as target
using (select @clockDate, @userName) as source (ClockDate, UserName)
on (target.ClockDate = source.ClockDate and target.UserName = source.UserName)
when matched then
update
set BreakOut = getdate()
when not matched then
insert (ClockDate, UserName, BreakOut)
values (getdate(), source.UserName, getdate());
Since the question mentioned third-party libraries and not all packages then you probably want to fall back to using wildcards.
A use case being: I just want to update all my packages that are obtained from the Github VCS, then you would just say:
go get -u github.com/... // ('...' being the wildcard).
This would go ahead and only update your github packages in the current $GOPATH
Same applies for within a VCS too, say you want to only upgrade all the packages from ogranizaiton A's repo's since as they have released a hotfix you depend on:
go get -u github.com/orgA/...
From plt.imshow()
official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 10000, 0, 10], aspect = 1000)
Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.
plt.imshow(data, origin = 'lower', extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')
To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1]
and y_max - y_min = y_res * data.shape[0]
, where extent = [x_min, x_max, y_min, y_max]
. By default, aspect = 1
, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower', extent = [0, 5, 0, 5])
The aspect of color pixel is x_res / y_res
. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])
) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.5)
The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.2)
Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.
For this particular query, why make expensive function calls for each row when you could just ask for values starting at the next higher second:
select *
from table
where date >= '2010-07-20 03:21:53'
you could search with
aptitude search intl
after you can choose the right one, for example
sudo aptitude install php-intl
and finally
sudo service apache2 restart
good Luck!
The spirit of the question, I think, was not truly answered. No, you cannot use a video tag to play rtsp streams as of now. The other answer regarding the link to Chromium guy's "never" is a bit misleading as the linked thread / answer is not directly referring to Chrome playing rtsp via the video tag. Read the entire linked thread, especially the comments at the very bottom and links to other threads.
The real answer is this: No, you cannot just put a video tag on an html 5 page and play rtsp. You need to use a Javascript library of some sort (unless you want to get into playing things with flash and silverlight players) to play streaming video. {IMHO} At the rate the html 5 video discussion and implementation is going, the various vendors of proprietary video standards are not interested in helping this move forward so don't count of the promised ease of use of the video tag unless the browser makers take it upon themselves to somehow solve the problem...again, not likely.{/IMHO}
For me placing my fonts folder as per location specified in bootstrap.css solved the problem
Mostly its fonts folder should be in parent directory of bootstrap.css file .
I faced this problem , and researching many answers , if anyone still in 2015 faces this problem then its either a CSS problem , or location mismatch for files .
The bug has already been solved by bootstrap
I wrote a little benchmark to compare ArrayLists with Arrays. On my old-ish laptop, the time to traverse through a 5000-element arraylist, 1000 times, was about 10 milliseconds slower than the equivalent array code.
So, if you're doing nothing but iterating the list, and you're doing it a lot, then maybe it's worth the optimisation. Otherwise I'd use the List, because it'll make it easier when you do need to optimise the code.
n.b. I did notice that using for String s: stringsList
was about 50% slower than using an old-style for-loop to access the list. Go figure... Here's the two functions I timed; the array and list were filled with 5000 random (different) strings.
private static void readArray(String[] strings) {
long totalchars = 0;
for (int j = 0; j < ITERATIONS; j++) {
totalchars = 0;
for (int i = 0; i < strings.length; i++) {
totalchars += strings[i].length();
}
}
}
private static void readArrayList(List<String> stringsList) {
long totalchars = 0;
for (int j = 0; j < ITERATIONS; j++) {
totalchars = 0;
for (int i = 0; i < stringsList.size(); i++) {
totalchars += stringsList.get(i).length();
}
}
}
If the table has an ID
:
const tableObject = document.getElementById(tableId);
const rowCount = tableObject[1].childElementCount;
If the table has a Class
:
const tableObject = document.getElementsByClassName(tableClass);
const rowCount = tableObject[1].childElementCount;
If the table has a Name
:
const tableObject = document.getElementsByTagName('table');
const rowCount = tableObject[1].childElementCount;
Note: index 1
represents <tbody>
tag
You can do both in code and XML. Only 4 basic things to be set.
e.g.
android:shadowColor="@color/text_shadow_color"
android:shadowDx="-2"
android:shadowDy="2"
android:shadowRadius="0.01"
This draws a prominent shadow on left-lower side of text. In code, you can add something like this;
TextView item = new TextView(getApplicationContext());
item.setText(R.string.text);
item.setTextColor(getResources().getColor(R.color.general_text_color));
item.setShadowLayer(0.01f, -2, 2, getResources().getColor(R.color.text_shadow_color));
I wanted to do the same thing. The best I could find was @MicTech's solution. However, as pointed out by @MotoWilliams this does not survive any updates made by Git to the .gitconfig file which replaces the link with a new file containing only the new settings.
I solved this by writing the following PowerShell script and running it in my profile startup script. Each time it is run it copies any settings that have been added to the user's .gitconfig to the global one and then replaces all the text in the .gitconfig file with and [include] header that imports the global file.
I keep the global .gitconfig file in a repo along with a lot of other global scripts and tools. All I have to do is remember to check in any changes that the script appends to my global file.
This seems to work pretty transparently for me. Hope it helps!
Sept 9th: Updated to detect when new entries added to the config file are duplicates and ignore them. This is useful for tools like SourceTree which will write new updates if they cannot find existing ones and do not follow includes.
function git-config-update
{
$localPath = "$env:USERPROFILE\.gitconfig".replace('\', "\\")
$globalPath = "C:\src\github\Global\Git\gitconfig".replace('\', "\\")
$redirectAutoText = "# Generated file. Do not edit!`n[include]`n path = $globalPath`n`n"
$localText = get-content $localPath
$diffs = (compare-object -ref $redirectAutoText.split("`n") -diff ($localText) |
measure-object).count
if ($diffs -eq 0)
{
write-output ".gitconfig unchanged."
return
}
$skipLines = 0
$diffs = (compare-object -ref ($redirectAutoText.split("`n") |
select -f 3) -diff ($localText | select -f 3) | measure-object).count
if ($diffs -eq 0)
{
$skipLines = 4
write-warning "New settings appended to $localPath...`n "
}
else
{
write-warning "New settings found in $localPath...`n "
}
$localLines = (get-content $localPath | select -Skip $skipLines) -join "`n"
$newSettings = $localLines.Split(@("["), [StringSplitOptions]::RemoveEmptyEntries) |
where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }
$globalLines = (get-content $globalPath) -join "`n"
$globalSettings = $globalLines.Split(@("["), [StringSplitOptions]::RemoveEmptyEntries)|
where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }
$appendSettings = ($newSettings | %{ $_.Trim() } |
where { !($globalSettings -contains $_.Trim()) })
if ([string]::IsNullOrWhitespace($appendSettings))
{
write-output "No new settings found."
}
else
{
echo $appendSettings
add-content $globalPath ("`n# Additional settings added from $env:COMPUTERNAME on " + (Get-Date -displayhint date) + "`n" + $appendSettings)
}
set-content $localPath $redirectAutoText -force
}
This gives you the root folder:
System.AppDomain.CurrentDomain.BaseDirectory
You can navigate from here using .. or ./ etc.. , Appending .. takes you to folder where .sln file can be found
For .NET framework (thanks to Adiono comment)
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"..\\..\\"))
For .NET core here is a way to do it (thanks to nopara73 comment)
Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")) ;
One possible solution can be
class Survey{
void renderSurvey(Question q) {
/*
Depending on the type of question (choice, dropdwn or other, I have to render
the question on the UI. The class that calls this doesnt have compile time
knowledge of the type of question that is going to be rendered. Each question
type has its own rendering function. If this is for choice , I need to access
its functions using q.
*/
if(q.getOption() instanceof ChoiceQuestionOption)
{
ChoiceQuestionOption choiceQuestion = (ChoiceQuestionOption)q.getOption();
boolean result = choiceQuestion.getMultiple();
//do something with result......
}
}
}
In my case the issue was not resolved because i did not restart my system. Please make sure you do restart your system.
This is a mismatch between assemblies: a DLL referenced from an assembly doesn't have a method signature that's expected.
Clean the solution, rebuild everything, and try again.
Also, be careful if this is a reference to something that's in the GAC; it could be that something somewhere is pointing to an incorrect version. Make sure (through the Properties of each reference) that the correct version is chosen or that Specific Version is set false.
Try this one -
CREATE PROCEDURE sp_ADD_USER_EXTRANET_CLIENT_INDEX_PHY
AS
BEGIN
DECLARE @ParLngId INT
SELECT TOP 1 @ParLngId = ParLngId
FROM dbo.T_Param
WHERE ParStrNom = 'Extranet Client'
IF (@ParLngId = 0)
BEGIN
INSERT INTO dbo.T_Param
VALUES ('PHY', 'Extranet Client', NULL, NULL, 'T', 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL)
RETURN SCOPE_IDENTITY()
END
ELSE BEGIN
RETURN @ParLngId
END
END
Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.
if (data == "" || data == undefined) {
alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var byteCharacters = atob(data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: 'application/pdf'
});
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else { // Directly use base 64 encoded data for rest browsers (not IE)
var base64EncodedPDF = data;
var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
window.open(dataURI, '_blank');
}
}
I think you can try this for calling in from a class
System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");
*----------------Sorry I oversight, for static function already answered the question by adrift*
System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");
Update
I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");
Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()
Solution (tested in static webmethod)
System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");
Worked
Just install regenerator-runtime with below command
npm i regenerator-runtime
add below line in startup file before you require server file
require("regenerator-runtime/runtime");
So far this has been working for me
If you have for instance in your package.json
file:
{
"name": "zig-zag",
"main": "lib/entry.js",
...
}
lib/entry.js
will be the main entry point to your package.
When calling
require('zig-zag');
in node, lib/entry.js
will be the actual file that is required.
Simple Get Request using HttpClient Class
using System.Net.Http;
class Program
{
static void Main(string[] args)
{
HttpClient httpClient = new HttpClient();
var result = httpClient.GetAsync("https://www.google.com").Result;
}
}
I use this script in bash:
#!/bin/bash
now=$(date +"%b%d-%Y-%H%M%S")
FILE="$1"
name="${FILE%.*}"
ext="${FILE##*.}"
cp -v $FILE $name-$now.$ext
This script copies filename.ext to filename-date.ext, there is another that moves filename.ext to filename-date.ext, you can download them from here. Hope you find them useful!!
Option #1: Try invalidateOptionsMenu()
. I don't know if this will force an immediate redraw of the action bar or not.
Option #2: See if getActionView()
returns anything for the affected MenuItem
. It is possible that showAsAction
simply automatically creates action views for you. If so, you can presumably enable/disable that View
.
I can't seem to find a way to get the currently set Menu to manipulate it except for in onPrepareOptionMenu.
You can hang onto the Menu
object you were handed in onCreateOptionsMenu()
. Quoting the docs:
You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.
Don't know the nature of your app, but I have seen this error manifested multiple times because of a connection pool leak, so that would be worth checking out. On Linux, socket connections consume file descriptors as well as file system files. Just a thought.
seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.
You may directly right-click on the table name - that also shows the "Import Data.." option.Then you can follow few simple steps & succeed.
Do anyone know how to import a new table with data from excel?